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();
//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;