Tuesday, April 04, 2006

Handy Method for Serializing objects to Xml

In many of my recent projects, I have come across serialization of objects to xml.
I am sure thats a very common thing these days with so many stuff going on with respect to interoperability and platform independance air all around.

Everytime I came across this, I saw myself playing with the memory stream and xml serialization classes. To avoid all these nitty gritties, I have written just a very small function that will help us do just this.

I hope it will help somebody save time doing this thing -

==============================
public static XmlDocument SerializeObject(System.Type type, Object obj)
{
try
{
System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
System.IO.MemoryStream stream = new System.IO.MemoryStream();
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(type);
serializer.Serialize(stream, obj);
byte[] buffer = stream.GetBuffer();
string xmlDoc = System.Text.ASCIIEncoding.ASCII.GetString(buffer).Trim();
xDoc.LoadXml(xmlDoc);
return xDoc;
}
catch (Exception ex)
{
return null;
}
}
==============================

This function does not have any requirements for namespace imports and can be used as a static method from your helper library.

Enjoy!