Serialization using C#

Posted on August 8, 2008. Filed under: Language features | Tags: , , , , , |

Serialization using C#

Steps
1. Create a Sample class library
2. Implement custom XML attributes
3. Write Client Call to serialize to XMLString

Example
Create a Sample class library & Implement custom XML attributes

namespace ExpShoppingList
{
[XmlRoot("shoppingList")]
public class ShoppingList
{
    private ArrayList listShopping;

    public ShoppingList()
    {
        listShopping = new ArrayList();
    }

    [XmlElement("item")]
    public Item[] Items
    {
        get
        {
            Item[] items = new Item[listShopping.Count];
            listShopping.CopyTo(items);
            return items;
        }
        set
        {
            if (value == null) return;
            Item[] items = (Item[])value;
            listShopping.Clear();
            foreach (Item item in items)
                listShopping.Add(item);
        }
    }

    public int AddItem(Item item)
    {
        return listShopping.Add(item);
    }

    public void LoadData()
    {
        this.AddItem(new Item(“eggs”, 1.49));
        this.AddItem(new Item(“ground beef”, 3.69));
        this.AddItem(new Item(“bread”, 0.89));
    }
}

// Items in the shopping list
public class Item
{
    private string _name;
    [XmlAttribute("name")]
    public string name
    {
        get { return _name; }
        set { _name = value; }
    }
    [XmlAttribute("price")]
    public double price;

    public Item()
    {
    }
    public Item(string Name, double Price)
    {
        _name = Name;
        price = Price;
    }
}

2. Create a Client Porject, which will Call to Serialize the instantiationed object to string

namespace ExportClassTest
{
    class Program
    {
        static void Main(string[] args)
        {

            ExpShoppingList.ShoppingList myList = new ExpShoppingList.ShoppingList();
            myList.LoadData();

            // Serialization
            System.Xml.Serialization.XmlSerializer x = new XmlSerializer(typeof(ExpShoppingList.ShoppingList));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            x.Serialize(ms, myList);
            ms.Position = 0;
            ms.Flush() ;
            StreamReader sr = new StreamReader(ms);

            string s = sr.ReadToEnd();

           //Console.ReadLine();
        }
    }
}

Make a Comment

Make a Comment: ( None so far )

blockquote and a tags work here.

Liked it here?
Why not try sites on the blogroll...