Serialize/Deserialize Xml: deal with element list : Xml serialization « XML « C# / CSharp Tutorial






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

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

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

  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;
  }
}


  New Catalog
  2008-03-25
  
    
      Product 1
      42.99
      false
    
    
      Product 2
      202.99
      false
    
  








30.30.Xml serialization
30.30.1.XML serialization with namespace setting
30.30.2.Serialize/Deserialize Xml: deal with element list
30.30.3.Specify the XmlRoot and XmlAttribute for XML serialization
30.30.4.Specify format and indentation for object XML serialization
30.30.5.Using XmlSerializer to Serialize a Linq object
30.30.6.XML Serialization Sample
30.30.7.Serialization of an object marked with XmlAttribute and XmlIgnore
30.30.8.Serialize a list of object to Xml with Linq
30.30.9.Xml Serialization for Enum
30.30.10.Xml Serialization for DateTime value
30.30.11.Assign XmlArrayAttribute to two arrays, and serializes a class instance that contains those arrays.
30.30.12.XmlTextAttribute with type string informs the XmlSerializer that strings should be serialized as XML text