Go to DotNetFunda.com
 Online : 2163 |  Welcome, Guest!   Login
 
Home > Articles > ASP.NET > How to Serialize and DeSerialize an object into XML

  • Download the OOPS, ASP.NET and ADO.NET Training Videos for FREE, click here.

Submit Article | Articles Home | Search Articles |

How to Serialize and DeSerialize an object into XML

 Posted on: 7/10/2008 7:21:53 AM by SheoNarayan | Views: 20118 | 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.

.NET Training Videos!
Buy online comprehensive training video pack just for $35.00 only, see what's inside it.

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


If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Interesting?   Share and Bookmark this kick it on DotNetKicks.com


About Sheo Narayan

Experience:8 year(s)
Home page:http://www.snarayan.com
Member since:Tuesday, July 08, 2008
Level:HonoraryPlatinum
Status: [Administrator]
Biography:Throughout 1st in all educational exams.
Major qualifications: HDCS, ADCA, MCA, MCTS
Developing and architecting applications in Microsoft technologies since year 2001.
Location: Hyderabad, India
 Latest post(s) from SheoNarayan

   ◘ Common operation with Files and Folders in ASP.NET posted on 9/4/2009 4:23:03 PM
   ◘ Working with CustomValidator control in ASP.NET posted on 8/19/2009 9:27:43 AM
   ◘ Backup and Restore database in ASP.NET posted on 8/7/2009 5:30:24 PM
   ◘ Passing data between layers using Generic list collection posted on 7/19/2009 7:28:40 AM
   ◘ jQuery and ASP.NET AJAX UpdatePanel posted on 7/17/2009 6:53:04 PM


Submit Article

About Us | The Team | Advertise | Contact Us | Feedback | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you found copied contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
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)