Subscribe

RSS Feed (xml)

Use XML Serialization with Custom Objects

The XmlSerializer class allows you to convert objects to XML data, and vice versa. This process is used natively by Web services and provides a customizable serialization mechanism that won't require a single line of custom code. The XmlSerializer class is even intelligent enough to correctly create arrays when it finds nested elements.

The only requirements for using XmlSerializer are as follows:

  • The XmlSerializer only serializes properties and public variables.

  • The classes you want to serialize must include a default zero-argument constructor. The XmlSerializer uses this constructor when creating the new object during deserialization.

  • All class properties must be readable and writable. This is because XmlSerializer uses the property get accessor to retrieve information, and the property set accessor to restore the data after deserialization.

To use XML serialization, you must first mark up your data objects with attributes that indicate the desired XML mapping. These attributes are found in the System.Xml.Serialization namespace and include the following:

  • XmlRoot Specifies the name of the root element of the XML file. By default, XmlSerializer will use the name of the class. This attribute can be applied to the class declaration.

  • XmlElementIndicates the element name to use for a property or public variable. By default, XmlSerializer will use the name of the property or public variable.

  • XmlAttributeIndicates that a property or public variable should be serialized as an attribute, not an element, and specifies the attribute name.

  • XmlEnumConfigures the text that should be used when serializing enumerated values. If you don't use XmlEnum, the name of the enumerated constant will be used.

  • XmlIgnoreIndicates that a property or public variable should not be serialized.

Here's the class code that you might use:

using System;
using System.Xml.Serialization;

[XmlRoot("productCatalog")]
public class ProductCatalog {

    [XmlElement("catalogName")]
    public string CatalogName;
    
    // Use the date data type (and ignore the time portion in the 
    // serialized XML).
    [XmlElement(ElementName="expiryDate", DataType="date")]
    public DateTime ExpiryDate;
    
    // Configure the name of the tag that holds all products,
    // and the name of the product tag itself.
    [XmlArray("products")]
    [XmlArrayItem("product")]
    public Product[] Products;

    public ProductCatalog() {
        // Default constructor for deserialization.
    }

    public ProductCatalog(string catalogName, DateTime expiryDate) {
        this.CatalogName = catalogName;
        this.ExpiryDate = expiryDate;
    }
}

public class Product {

    [XmlElement("productName")]
    public string ProductName;
    
    [XmlElement("productPrice")]
    public decimal ProductPrice;
    
    [XmlElement("inStock")]
    public bool InStock;
    
    [XmlAttributeAttribute(AttributeName="id", DataType="integer")]
    public string Id;

    public Product() {
        // Default constructor for serialization.
    }

    public Product(string productName, decimal productPrice) {
        this.ProductName = productName;
        this.ProductPrice = productPrice;
    }
}

Notice that these classes use the XML serialization attributes to rename element names (using Pascal casing in the class member names, and camel casing in the XML tag names), indicate data types that aren't obvious, and specify how <product> elements will be nested in the <productCatalog>.

Using these custom classes and the XmlSerializer object, you can translate XML into objects and vice versa. Here's the code you would need to create a new ProductCatalog object, serialize the results to an XML document, deserialize the document back to an object, and then display the XML document.

using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

public class SerializeXml {

    private static void Main() {

        // Create the product catalog.
        ProductCatalog catalog = new ProductCatalog("New Catalog",
          DateTime.Now.AddYears(1));
        Product[] products = new Product[2];
        products[0] = new Product("Product 1", 42.99m);
        products[1] = new Product("Product 2", 202.99m);
        catalog.Products = products;

        // Serialize the order to a file.
        XmlSerializer serializer = new XmlSerializer(typeof(ProductCatalog));
        FileStream fs = new FileStream("ProductCatalog.xml", FileMode.Create);
        serializer.Serialize(fs, catalog);
        fs.Close();

        catalog = null;

        // Deserialize the order from the file.
        fs = new FileStream("ProductCatalog.xml", FileMode.Open);
        catalog = (ProductCatalog)serializer.Deserialize(fs);

        // Serialize the order to the Console window.
        serializer.Serialize(Console.Out, catalog);
        Console.ReadLine();
    }
}

Technorati :

No comments:

Post a Comment

Archives

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail