Serialize and Deserialize object using C#

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();
doc.LoadXml(sb.ToString());
//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;

 

Class:

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

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s