Demonstrate the basics of XML serialization - CSharp XML

CSharp examples for XML:XML Serialization

Description

Demonstrate the basics of XML serialization

Demo Code

//Compilation instructions
// csc Main.cs /r:System.dll,System.Xml.dll,System.Xml.Serialization.dll
using System;/* www  .  jav a  2  s.c om*/
using System.Xml;
using System.Xml.Serialization;
using System.Collections;
using System.IO;
[XmlRoot("purchase-order")]
public class PurchaseOrder {
   private ArrayList   m_Items;
   public PurchaseOrder( ) {
      m_Items = new ArrayList();
   }
   [XmlElement("item")]
   public Item[] Items {
      get {
         Item[] items = new Item[ m_Items.Count ];
         m_Items.CopyTo( items );
         return items;
      }
      set {
         Item[] items = (Item[])value;
         m_Items.Clear();
         foreach( Item i in items )
            m_Items.Add( i );
         }
      }
      public void AddItem( Item item ) {
         m_Items.Add( item );
      }
      public Item this[string sku] {
         get {
            //locate the item by sku
            foreach( Item i in m_Items )
               if( i.sku == sku )
            return i;
         throw( new Exception("Item not found") );
      }
   }
   public void DisplayItems( ) {
      foreach( Item i in m_Items )
         Console.WriteLine( i );
      }
   }
   public class Item {
      [XmlAttribute("sku")]   public string  sku;
      [XmlAttribute("desc")]  public string  desc;
      [XmlAttribute("price")] public double  price;
      [XmlAttribute("qty")]   public int     qty;
      public Item( ) {  }
      public Item( string Sku, string Desc, double Price, int Qty ) {
         sku = Sku;
         desc = Desc;
         price = Price;
         qty = Qty;
      }
      public override string ToString( ) {
         object[] o = new object[] { sku, desc, price, qty };
         return string.Format("{0,-5} {1,-10} ${2,5:#,###.00} {3,3}", o);
      }
   }
   public class POExample {
      public static void Main( ) {
         PurchaseOrder po = new PurchaseOrder( );
         po.AddItem( new Item("123","A",.15,100) );
         po.AddItem( new Item("321","B", 7.50, 25) );
         po.AddItem( new Item("111","C", 1.35, 10) );
         po.DisplayItems( );
         XmlSerializer s = new XmlSerializer( typeof( PurchaseOrder ) );
         TextWriter w = new StreamWriter("po.xml");
         s.Serialize( w, po );
         w.Close();
         PurchaseOrder po2 = new PurchaseOrder( );
         TextReader r = new StreamReader( "po.xml" );
         po2 = (PurchaseOrder)s.Deserialize( r );
         r.Close( );
         Console.WriteLine("Deserialization complete");
         po2.DisplayItems();
      }
}

Result


Related Tutorials