Use XML Serialization with Custom Objects : Xml Serialization : XML C# Source Code


Custom Search

C# Source Code » XML » Xml Serialization »

 

Use XML Serialization with Custom Objects








    


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

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

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

    [XmlArray("products")]
    [XmlArrayItem("product")]
    public Product[] Products;

    public ProductCatalog() { }
    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;
    }
}


public class MainClass {
    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);
    }
}



           
       
    
   
  
   







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo XML
» Xml Serialization