In C#, converting any Object into stream of bytes to persist the state of Object is called Serialization. Converting stream of bytes into specific Object is called deserialization. That means in deserialization we are reconstructing the object.
There are three different types of Serialization, those are BinaryFormatter, SoapFormatter, and XmlSerializer. Today we discuss about how to serialize the object by using XmlSerializer with simple example.
Open Microsoft Visual Studio 2013 => Create some web application & name it as CSharpXmlSerializer
Add one class and name it as Employee with two properties as shown below.
namespace CSharpXmlSerializer
{
public class Employee
{
public int Id
{
get;
set;
}
public string Name
{
get;
set;
}
}
}
First create some object for the class and serialize that object as shown below.
using System;
using System.IO;
using System.Xml.Serialization;
namespace CSharpXmlSerializer
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Employee objEmployee = new Employee();
objEmployee.Id = 101;
objEmployee.Name = "Bob";
XMLSerialization(objEmployee);
}
private void XMLSerialization(Object obj)
{
XmlSerializer xml = new XmlSerializer(typeof(Employee));
using (Stream fStream = new FileStream(@"E:\XMLserialize.txt", FileMode.Create, FileAccess.Write, FileShare.None))
{
xml.Serialize(fStream, obj);
}
}
}
}
As shown above we are using System.Xml.Serialization namespace to serialize the object in XML format, System.IO namespace to save the serialization text into a file.
Run the application, it serializes the given object and saves in E:\XMLserialize.txt file. The content of the XMLserialize.txt as shown below.
<?xml version="1.0"?>
<Employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Id>101</Id>
<Name>Bob</Name>
</Employee>
We can deserialize the object from the Serialized data as shown below.
private void XMLDeSerialization()
{
XmlSerializer objDeserializer = new XmlSerializer(typeof(Employee));
TextReader reader = new StreamReader(@"E:\XMLserialize.txt");
object obj = objDeserializer.Deserialize(reader);
Employee objEmployee = (Employee)obj;
reader.Close();
}
In the above code, TextReader reading the XML content from E:\XMLserialize.txt file and XmlSerializer converting the text by using Deserialize() method into Object type. Then we can convert Object type into actual Employee class type. In this way we can get original object from the serialize content by using XmlSerializer class Deserialize() method.