How to Serialize and DeSerialize an object into XML

SheoNarayan
Posted by in ASP.NET category on for Advance level | Views : 122455 red flag

In this article, I am going to show how to Serialize and DeSerialize an object (can be a collection object or an object) into XML format using ASP.NET System.Xml.Serialization.XmlSerializer class.
Introduction

Before I explain how to Serialize and DeSerialize an object, let me tell you why to serialize. We should serialize an object if we want to store the object instance into the disk or we  want to store the object into Session or Cache (storing serialized object into Cache or Session works faster than storing the object directly) or pass the object between applications regardless of which platform they have hosted on and technology they are built in.

Now why to use XML Serialization? As XML is an open standard, XML stream can be processed by any application, as needed regardless of platform. XML Serialization coverts (Serializes) the public fields and properties of an object, or parameters and return values of method, into an XML stream.

Background

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;

}

Setting values for the public variables

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

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.

/// <summary>

/// Serialize an object

/// </summary>

/// <param name="obj"></param>

/// <returns></returns>

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>

How to DeSerialize an Object

To DeSerialize an object you need an instance of StringReader, XmlReader and XmlSerializer class in order to read the xml data (Serialized data), read it into XmlReader and DeSerialize it respectively. So in brief my function to DeSerialize the object looks like following.

/// <summary>

/// DeSerialize an object

/// </summary>

/// <param name="xmlOfAnObject"></param>

/// <returns></returns>

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;

 

Conclusion

In this article, I have described how to Serialize and DeSerialize an object using XmlSerializer class. Hope this will help someone. Thanks and Happy Coding !!!

Reference: For more indepth knowledge on Serializatiion you can refer to MSDN at http://msdn.microsoft.com/en-us/library/aa720602(VS.71).aspx

Page copy protected against web site content infringement by Copyscape

About the Author

SheoNarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com

Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Posted by: Narla.Venkatesh on: 5/28/2013 | Points: 25
Correct the convert spelling in Introduction section

Login to post response

Comment using Facebook(Author doesn't get notification)