Use XML Serialization with Custom Objects - CSharp XML

CSharp examples for XML:XML Serialization

Description

Use XML Serialization with Custom Objects

Demo Code


using System;//from   ww  w  . ja v  a 2 s  . co m
using System.Xml;
using System.Xml.Serialization;
using System.IO;

public class SerializeXml
{
    private static void Main()
    {
        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;

        XmlSerializer serializer = new XmlSerializer(typeof(ProductCatalog));
        FileStream fs = new FileStream("ProductCatalog.xml", FileMode.Create);
        serializer.Serialize(fs, catalog);
        fs.Close();

        catalog = null;
        fs = new FileStream("ProductCatalog.xml", FileMode.Open);
        catalog = (ProductCatalog)serializer.Deserialize(fs);

        serializer.Serialize(Console.Out, catalog);
    }
}


[XmlRoot("productCatalog")]
public class ProductCatalog
{
    [XmlElement("catalogName")]
    public string CatalogName;

    [XmlElement(ElementName = "expiryDate", DataType = "date")]
    public DateTime ExpiryDate;

    [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()
    {
    }

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

Result


Related Tutorials