Go to DotNetFunda.com
  Welcome, Guest!  
LoginLogin  
{ Submit resources and get monthly gifts !!! }
Submit: Article | Interview Question | Tips | Joke | Question | Link || Search  
 Skip Navigation Links Home > Articles > How to Serialize and DeSerialize an object into XML

All Articles | Post Articles |  Subscribe to RSS

How to Serialize and DeSerialize an object into XML

 Posted on: 7/10/2008 7:21:53 AM by SheoNarayan | Views: 6044 | Category: ASP.NET | Level: Advance | Print Article |
ASP.NET 3.5 Hosting and MS SQL 2008!
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




 Bookmark and Share kick it on DotNetKicks.com

About Sheo Narayan

Experience:6 year(s)
Home page:http://sheonarayan.blogspot.com/
Member since:Tuesday, July 08, 2008
Biography:Throughout 1st in all educational exams.
Major qualifications: HDCS, ADCA, MCA
Location: Hyderabad, India
 Latest post(s) from SheoNarayan

   ◘ Getting selected record key value from ASP.NET Data Controls posted on 10/4/2008 9:27:54 PM
   ◘ Working with Collections - Generic List posted on 10/3/2008 9:54:04 AM
   ◘ Working with Value Types Variables posted on 9/20/2008 10:06:20 PM
   ◘ Working with Collections - ArrayList posted on 9/20/2008 8:04:52 AM
   ◘ Solution of problem having same method name in two interfaces inheriting a class posted on 9/7/2008 8:58:28 AM


Question: Why to use www.dotnetfunda.com google search?
Answer: This search has been especially optimized to search technical articles. You may find to-the-point results in comparison with other search.
Google
About Us | Contact Us | Privacy Policy and Terms of Use | Link Exchange | Members | Go Top
All rights reserved to DotNetFunda.com. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks.
This site is best viewed with a resolution of 1280x720 (or higher) and Microsoft Internet Explorer 6.0+ or Firefox 2.0+.