Feb 28, 2012

How to convert the object to xml and xml to object.


Convert the object to xml using XML Serializer class. XML Serialization coverts (Serializes) the public fields and properties of an object, or parameters and return values of method, into an XML stream.

The following namespaces are required for this xml serialization.
using System.IO;
using System.Xml;
using System.Xml.Serialization;

To show this conversion, creating sample class called student. It looks like following
Student class:-

/// class for student properties
public class Student
{
public int StudentId { set; get; }
public string StudentName { set; get; }
public DateTime DOB { set; get; }
public string address { set; get; }
}


Object to Xml:-
Now create the following class instances for the serialization of the object
1) XmlDocument object to represents the converted xml
2) XmlSerializer object to covert (Serialize) the public fields and properties of an object, or parameters and
return values of method, into an XML stream.
3) MemoryStream object to hold the serialized stream in memory.
After creating all the above instances call the serialize method of XmlSerializer object with parameters stream and object, it converts the object to stream and store into passed stream object and set the stream position to begin.
Now load this stream in to xml document by calling the Load() of XmlDocument object.

/// Method to convert the object to xml using XmlSerializer.
public static XmlDocument ConvertToXml(Student student)
{
MemoryStream ObjStream = new MemoryStream();
XmlDocument ObjDocument = new XmlDocument();
XmlSerializer ObjSerializer = new XmlSerializer(student.GetType());
ObjSerializer.Serialize(ObjStream, student);
ObjStream.Seek(0, SeekOrigin.Begin);
ObjDocument.Load(ObjStream);
return ObjDocument;
}

Xml to object:-
Deserialize to the object from the xmlDocument object or xml file using the Deserialize method of XmlSerializer class and StringReader object which holds the xml content.

/// Method to convert the xml to object using XmlSerializer.
public static Student ConvertToObject(XmlDocument document)
{
Student ObjStudent = new Student();
StringReader ObjReader = new StringReader(document.InnerXml);
XmlSerializer ObjSerializer = new XmlSerializer(typeof(Student));
ObjStudent = (Student)ObjSerializer.Deserialize(new XmlTextReader(ObjReader));
return ObjStudent;
}

Call these methods form any of the class like following

/// Fill the student class object with values
Student student = new Student();
student.StudentId = 1;
student.StudentName = "Tom Smith";
student.DOB = DateTime.Now;
student.address = "Chennai,India";

/// Call the Convert to xml method
XmlDocument xmlDocument = new XmlDocument();
xmlDocument = XmlOperation.ConvertToXml(student);

/// Call the Convert to object method
Student student1 = new Student();
student1 = XmlOperation.ConvertToObject(xmlDocument);