XML Serialization using C#
Introduction
Serialization is a process of storing state of an object
to some media like disk file or stream. Few weeks back we saw how to serialize objects to disk file in binary
format
.
.NET further provides a way to serialize objects in XML format. Thus
objects can be converted into XML documents (serialization) and later on can be constructed
back from the XML documents (deserialization). This article demonstrates how to use XML serialization
techniques using C#.
Namespaces involved
Following namespaces are involved in serialization
process :
-
System.Xml.Serialization
-
System.IO
Example - XML Serialization and deserialization
Following example shows how to serialize objects into XML documents and later read
them back.
using System;
using System.Xml.Serialization;
using System.IO;
[XmlRoot(ElementName="Employee")]
public class Employee
{
private string m_id;
private string m_name;
private int m_age;
private string[] m_prevcomp;
[XmlAttribute(AttributeName="EmpID")]
public string EmpID
{
get{return m_id;}
set{m_id=value;}
}
[XmlElement(ElementName="Name")]
public string Name
{
get{return m_name;}
set{m_name=value;}
}
[XmlElement(ElementName="Age")]
public int Age
{
get{return m_age;}
set{m_age=value;}
}
[XmlElement(ElementName="PreviousCompany")]
public string[] PreviousCompanies
{
get
{
return m_prevcomp;
}
set
{
m_prevcomp=value;
}
}
public static void Main()
{
string[] comps={"comp1","comp2"};
Employee e=new Employee();
e.EmpID="EMP1001";
e.Name="bipin";
e.Age=26;
e.PreviousCompanies=comps;
StreamWriter writer=File.CreateText
(@"d:\bipin\vs.net\c#\serialization\sample.xml");
XmlSerializer x=new XmlSerializer(typeof(Employee));
Console.WriteLine("Serialization Start...");
x.Serialize(writer,e);
writer.Close();
Console.WriteLine("Serialization Complete...");
Employee e1=new Employee();
StreamReader reader=File.OpenText
(@"d:\bipin\vs.net\c#\serialization\sample.xml");
x=new XmlSerializer(typeof(Employee));
Console.WriteLine("Deserialization Start...");
e1=(Employee)x.Deserialize(reader);
reader.Close();
Console.WriteLine("Deserialization Complete...");
Console.WriteLine("Deserialized Object Employee Name :" +
e1.Name);
Console.ReadLine();
}
}
We have created Employee class that stores Employee ID, Name, Age and Previous
employers in variables m_id, m_name, m_age and m_prevcomp (array) respectively. We have
created public properties to encapsulate each f these variables. We want to store
the state of an object of Employee class in XML format.
The first step is to mark various elements using serialization attributes.
Following is a summary of attributes used in previous example :
Attribute |
Purpose |
XmlRoot(ElementName="Employee") |
This attribute marks the root element of the
resulting XML document. There can be only one root element in an XML
document. |
XmlAttribute(AttributeName="EmpID") |
This attribute marks the property to persist as XML attribute in the
resulting XML document. |
XmlElement(ElementName="Name") |
This attribute marks a property as an XML
element. The ElementName property of the attribute is used to set the
element name in the resulting XML document. It can be any valid XML
element name. |
Once you mark various attributes, you are ready to
serialize the class. In our example code from Main method does serialization as
follows :
StreamWriter writer=File.CreateText
(@"d:\bipin\vs.net\c#\serialization\sample.xml");
XmlSerializer x=new XmlSerializer(typeof(Employee));
x.Serialize(writer,e);
First we have created a text file in which our class
will be serialized. Next, we have created an instance of XmlSerializer class.
Finally, we call Serialize method on this instance passing it the file stream
and object instance.
Here is how the XML file looks :
<?xml version="1.0" encoding="utf-8"?>
<Employee xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xmlns:xsd="http://www.w3.org/2001/XMLSchema" EmpID=
"EMP1001">
<Name>bipin</Name>
<Age>26</Age>
<PreviousCompany>comp1</PreviousCompany>
<PreviousCompany>comp2</PreviousCompany>
</Employee>
You can read the XML file created back into an object
like this :
StreamReader reader=File.OpenText
(@"d:\bipin\vs.net\c#\serialization\sample.xml");
x=new XmlSerializer(typeof(Employee));
e1=(Employee)x.Deserialize(reader);
Simply open the text file to which we previously stored
our object and call Deserialize method on the XmlSerializer instance.