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.

//Form


private void button1_Click
(object sender, EventArgs e)
{
Employees<Employee> emps = new Employees<Employee>();
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<Employee> 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<Employee>));
FileStream fs = new FileStream(filename, FileMode.Open);
object obj = xmlSer.Deserialize(fs);
Employees<Employee> emps = (Employees<Employee>)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<T>: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);
}
}
}


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: