XML Serialization/Deserialization

class Test

{

  [STAThread]static void Main(string[] args)

  {

    ItemList myList = new ItemList();

    myList.AddItem(new Item(“first”, 1));

    myList.AddItem(new Item(“second”, 2));

    myList.AddItem(new Item(“third”, 3));

    // Serialization

    XmlSerializer xs = new XmlSerializer(typeof(ItemList));

    TextWriter tw = new StreamWriter(@”c:\list.xml”);

    xs.Serialize(tw, myList);

    tw.Close();

    // Deserialization

    ItemList newList;

    TextReader tr = new StreamReader(@”c:\list.xml”);

    newList = (ItemList)xs.Deserialize(tr);

    tr.Close();

  }

}

[XmlRoot(“itemList”)]

public class ItemList

{

  private ArrayList listItem;

  public ItemList()

  {

    listItem = new ArrayList();

  }

  [XmlElement(“item”)]

  public Item[] Items

  {

    get

    {

      Item[] items = new Item[listItem.Count];

      listItem.CopyTo(items);

      return items;

    }

    set

    {

      if (value == null) return;

      Item[] items = (Item[])value;

      listItem.Clear();

      foreach (Item item in items)

      {

        listItem.Add(item);

      }

    }

  }

  public int AddItem(Item item)

  {

    return listItem.Add(item);

  }

}

public class Item

{

  [XmlAttribute(“name”)]  public string Name;  [XmlAttribute(“id”)]

  public int Id;

  public Item(string name, int id)

  {

    Name = name;

    Id = id;

  }

}

Resulting XML:

<itemList>

  <item name=first id=1/>

  <item name=second id=2/>

  <item name=third id=3/>

</itemList>

Advertisements