Serialize and Deserialize object using C#   Leave a comment

Below shown is the very simple and easiest code example to serialize and deserialize the class object using XmlSerializer.

System imports are:

using System.Xml;
using System.IO;
using System.Xml.Serialization;


Actual Code:

clsPerson p = new clsPerson();
p.FirstName = "Jeff";
p.MI = "A";
p.LastName = "Price";
// Assuming p is an instance of an object
XmlSerializer ser = new XmlSerializer(p.GetType());
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringWriter writer = new System.IO.StringWriter(sb);
ser.Serialize(writer, p);

XmlDocument doc = new XmlDocument();
//Assuming doc is an XML document containing a serialized object and objType is a System.Type set to the type of the object.
XmlNodeReader reader = new XmlNodeReader(doc.DocumentElement);
System.Type objType = p.GetType();
XmlSerializer ser1 = new XmlSerializer(objType);
object obj = ser1.Deserialize(reader);
// Then you just need to cast obj into whatever type it is eg:
clsPerson p1 = (clsPerson)obj;



public class clsPerson {
        public string FirstName;
        public string MI;
        public string LastName;

Posted October 22, 2014 by Izharuddin Shaikh in C#

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: