Thursday, February 18, 2010

Serialize Objects using XmlSerializer class

Xml Serialization
--------------------------------------
Serialization is the process of converting an object to a format that can be transfer through a network or can be save to a location(file or DB).
The serialized data contains the object's informations like Version,Culture,PublicKeyToken,Type etc.
Deserialization is the reverse process of serialization, that is reconstructing the object from the serialized state to its original state.

Here is an eg:

A class "Employee" and its collection class "Employees". I marked these classes as Serializable with the [Serializable] attribute.
and also i am using XmlSerializer class to Serialize and Deserialize this object.

private void button1_Click
(object sender, EventArgs e)
{
Employees emps = new Employees();
emps.Add(new Employee("1", "Sabu"));
emps.Add(new Employee("2", "Litson"));

String pth = @"E:\Test.xml";
XmlSerialize(emps, pth);
XmlDeserialize(pth);
}

public void XmlSerialize(Employees emps, String filename)
{
System.IO.Stream ms = File.OpenWrite(filename);
System.Xml.Serialization.XmlSerializer xmlSer = new System.Xml.Serialization.XmlSerializer(emps.GetType());
xmlSer.Serialize(ms, emps);
ms.Flush();
ms.Close();
ms.Dispose();
xmlSer = null;
}

public void XmlDeserialize(String filename)
{
System.Xml.Serialization.XmlSerializer xmlSer =
new System.Xml.Serialization.XmlSerializer(typeof(Employees));
FileStream fs = new FileStream(filename, FileMode.Open);
object obj = xmlSer.Deserialize(fs);
Employees emps = (Employees)obj;
MessageBox.Show(emps[1].Name);
}


//Classes

[Serializable]
public class Employee
{

public Employee(String id, String name)
{
_ID = id;
_Name = name;
}

private String _ID = String.Empty;
private String _Name = String.Empty;

public String ID
{
get
{
return _ID;
}
set
{
_ID = value;
}
}

public String Name
{
get
{
return _Name;
}
set
{
_Name = value;
}
}
}

[Serializable]
public class Employees:CollectionBase
{
//Constructor
public Employees()
{

}

//Add function
public void Add(T objT)
{
this.List.Add(objT);
}

//Indexer
public T this[int i]
{
get
{
return (T) this.List[i];
}
set
{
this.List.Add(value);
}
}
}

No comments:

Post a Comment