Go to DotNetFunda.com
 Welcome, Guest!  
LoginLogin  
Take a break and be productive! read technical jokes.
 Skip Navigation Links Home > Articles > ASP.NET > How to Serialize and DeSerialize an object into XML

All Articles | Submit Article |

How to Serialize and DeSerialize an object into XML

 Posted on: 7/10/2008 7:21:53 AM by SheoNarayan | Views: 12209 | Category: ASP.NET | Level: Advance | Print Article
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.

 Get Career Counseling  
DotNetFunda.Com brings you a FREE Career Counseling section where you can ask any type of career related question. Ask now!

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


Interesting?   Bookmark and Share


About Sheo Narayan

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

   ◘ Ensuring button is clicked only once, Confirmation and Please wait message for ASP.NET Form posted on 7/3/2009 3:34:15 PM
   ◘ Setting up Start Options in Visual Studio and Visual Web Developer posted on 6/28/2009 7:53:02 AM
   ◘ Website vs Web Application - Embedded resources posted on 6/23/2009 10:10:20 PM
   ◘ Adding removing xml attribute from XML File in .NET posted on 6/21/2009 12:55:43 AM
   ◘ Working with Themes in ASP.NET posted on 6/8/2009 12:13:10 PM


 Submit Article

About Us | Contact Us | Privacy Policy | 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.
(Best viewed in IE 6.0+ or Firefox 2.0+ at 1024 * 768 or higher)