Thursday, 30 August 2012

.Net Tips, C# Tips : XML Deserialization with C# Examples and VB.Net Examples


Click Here to Download XMLSerializationAndDeserializationApplication.zip

Note : This application contains both serialize and deserialize exmples. Goto File menu and Download after click on download link.

In XML Deserialization you convert XML file data back in to custom class objects.
This is a reverse process of XML Serialization.
In previous example we serialize on object data in to XML now we take this Generated XML file and create class object from that.

This XML Serialization and Deserialization is very useful when communicating between to system where from one system object's data is converted into XML and transmit through network and at receiver end other system receive that xml data and back to converted object using deserialize.
This is useful when both end has different platform. I.e one end has .Net application and other end has JAVA or PHP or anyother patform applicaton.

Here is example for this.
In this example we took XML serialized file "ProductDetails.xml" and deserialize this into object with populating data back.
You can see in the output image that "ProductCategory" object fill from the "ProductDetails.xml" XML File.

C# Examples :
    [XmlRoot("productCategory")]
    public class ProductCategory
    {
        [XmlElement("categoryName")]
        public string CategoryName;

        [XmlElement("categoryDescription")]
        public string CategoryDescription;
        [XmlElement(ElementName = "launchDate", DataType = "date")]
        public DateTime LaunchDate;
        [XmlArray("products")]
        [XmlArrayItem("product")]
        public Product[] Products;
        public ProductCategory()
        {
            // Default constructor for deserialization.
        }
        public ProductCategory(string categoryName, string categoryDescription, DateTime launchDate)
        {
            this.CategoryName = categoryName;
            this.CategoryDescription = categoryDescription;
            this.LaunchDate = launchDate;
        }
    }
    public class Product
    {
        [XmlElement("productName")]
        public string ProductName;
        [XmlElement("productWeight")]
        public decimal ProductWeight;
        [XmlElement("productPrice")]
        public decimal ProductPrice;
                
        [XmlAttributeAttribute(AttributeName = "id")]
        public int Id;
        public Product()
        {

        }
        public Product(int productId, string productName, decimal productWeight , decimal productPrice)
        {
            this.Id =  productId;
            this.ProductName = productName;
            this.ProductWeight = productWeight;
            this.ProductPrice = productPrice;
            
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {

        ProductCategory objCategory;
        XmlSerializer objXMLSerializer = new XmlSerializer(typeof(ProductCategory));
        FileStream objFS = new FileStream(Server.MapPath("ProductDetails.xml"), FileMode.Open);
        objCategory = (ProductCategory)objXMLSerializer.Deserialize(objFS);
        objFS.Close();

    }

VB.net Examples :
    <XmlRoot("productCategory")> _
    Public Class ProductCategory
        <XmlElement("categoryName")> _
        Public CategoryName As String

        <XmlElement("categoryDescription")> _
        Public CategoryDescription As String
        <XmlElement(ElementName:="launchDate", DataType:="date")> _
        Public LaunchDate As DateTime
        <XmlArray("products")> _
        <XmlArrayItem("product")> _
        Public Products() As Product
        Public Sub New()

        End Sub
        Public Sub New(ByVal categoryName As String, ByVal categoryDescription As String, ByVal launchDate As DateTime)
            Me.CategoryName = categoryName
            Me.CategoryDescription = categoryDescription
            Me.LaunchDate = launchDate
        End Sub
    End Class
    Public Class Product
        <XmlElement("productName")> _
        Public ProductName As String
        <XmlElement("productWeight")> _
        Public ProductWeight As Decimal
        <XmlElement("productPrice")> _
        Public ProductPrice As Decimal

        <XmlAttributeAttribute(AttributeName:="id")> _
        Public Id As Integer
        Public Sub New()

        End Sub
        Public Sub New(ByVal productId As Integer, ByVal productName As String, ByVal productWeight As Decimal, ByVal productPrice As Decimal)
            Me.Id = productId
            Me.ProductName = productName
            Me.ProductWeight = productWeight
            Me.ProductPrice = productPrice

        End Sub
    End Class
  
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim objCategory As New ProductCategory
        Dim objXMLSerializer As New XmlSerializer(Type.GetType(objCategory.ToString()))
        Dim objFS As FileStream = New FileStream(Server.MapPath("ProductDetails.xml"), FileMode.Open)
        objCategory = objXMLSerializer.Deserialize(objFS)
        objFS.Close()
    End Sub

XML File ("ProductDetails.xml") :
<?xml version="1.0"?>
<productCategory xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <categoryName>Category 1</categoryName>
  <categoryDescription>Category for sports</categoryDescription>
  <launchDate>2012-08-29</launchDate>
  <products>
    <product id="1">
      <productName>Bat</productName>
      <productWeight>2</productWeight>
      <productPrice>20.39</productPrice>
    </product>
    <product id="2">
      <productName>Ball</productName>
      <productWeight>1</productWeight>
      <productPrice>2.90</productPrice>
    </product>
    <product id="3">
      <productName>Stumps</productName>
      <productWeight>3</productWeight>
      <productPrice>50.70</productPrice>
    </product>
  </products>
</productCategory>

Output : 
(To view original image , click on image)

Click Here to view "XML Serialization of Class Objects with C# Examples and VB.Net Examples". Click Here...

This is very useful .Net Tips.

For Beginning .Net articles. Click Here...

To learn more regarding XML. Click Here...

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.



No comments:

Post a Comment

Post a Comment