Wednesday, September 24, 2008

Serialize and DeSerialize an object into XML

Required namespace to Serialize and DeSerialize an object in this artilce are:
1. System.IO
2. System.Xml
3. System.Xml.Serialization

In order to show how to Serialize and DeSerialize an object, I will create a class called MyClass that will have two public variable named name and address. My code for this class is as follows

public class MyClass
{
public string name = string.Empty;
public string address = string.Empty;
}

I have set this class value as following:

MyClass myClass = new MyClass();
myClass.name = "Sheo Narayan";
myClass.address = "Washington DC, US";

How to Serialize an Object:

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

How to DeSerialize an Object

private object DeSerializeAnObject(string xmlOfAnObject)
{
MyClass myObject = new MyClass();
System.IO.StringReader read = new StringReader(xmlOfAnObject);
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(myObject.GetType());
System.Xml.XmlReader reader = new XmlTextReader(read);
try
{
myObject = (MyClass)serializer.Deserialize(reader);
return myObject;
}
catch
{
throw;
}
finally
{
reader.Close();
read.Close();
read.Dispose();
}
}

This function return an object so to covert that object into my class I will have to unbox it. In order to avoid boxing and unboxing, you can simply specify your class name as a parameter to these functions. To get my class from serialized xml I will call above function like following and extract its properties or use in the way i want.

MyClass deSerializedClass = (MyClass) DeSerializeAnObject(xmlObject);
string name = deSerializedClass.name;
string address = deSerializedClass.address;

Thats all

No comments: