How to Serialize an Object

To Serialize and object, we need few instances of the in-built classes. So lets first create an instance of a XmlDocument class from System.Xml namespace. Then create an instance of XmlSerializer class from System.Xml.Serialization namespace with parameter as the object type. Now just create an instance of the MemoryStream class from System.IO namespace that is going to help us to hold the serialized data. So all your instances are there, now you need to call their methods and get your serialzed object in the xml format. My function to Serialize an object looks like following.

private string SerializeAnObject(object obj) {
	System.Xml.XmlDocument doc = new XmlDocument();
	System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
	System.IO.MemoryStream stream = new System.IO.MemoryStream();
	try {
		serializer.Serialize(stream, obj);
		stream.Position = 0;
		doc.Load(stream);
		return doc.InnerXml;
	} catch {
		throw;
	} finally {
		stream.Close();
		stream.Dispose();
	}
}

This is a generic function and you can use this function to pass any type of object that can be serialized, even you can serialize a collection object. This method will return a string that is nothing but our serialized object in XML format. I will call my above function like this

string xmlObject = SerializeAnObject(myClass);

My class will look like following after serialization (XML contents).

<myclass
    xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <name>Sheo Narayan</name>
    <address>Washington DC, US</address>
</myclass>

 

Tagged . Bookmark the permalink.

Leave a Reply