Introducing DotNetFunda.com on mobile http://m.dotnetfunda.com ! Be with DotNetFunda.com on the go !
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 7164 |  Welcome, Guest!   Register  Login
Home > Articles > ASP.NET > How to Serialize and DeSerialize an object into XML

How to Serialize and DeSerialize an object into XML

Article posted by SheoNarayan on 7/10/2008 | Views: 59944 | Category: ASP.NET | Level: Advance 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

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

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

About Sheo Narayan

Experience:8 year(s)
Home page:http://www.snarayan.com
Member since:Tuesday, July 08, 2008
Level:HonoraryPlatinum
Status: [Microsoft_MVP] [Administrator]
Biography:Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001.

Connect me on Facebook | Twitter | LinkedIn | Blog

>> Write Response - Respond to this post and get points
Related Posts

when a user selects a row in a Grid that selected Row Hiding column value have to retrive.

If we could have accessed the Bind method ,that implicitly performs two-way binding, in the code-behind then we could have just override the RowDatabound event and assigned the value to the gridview's checkbox control using the Bind method. But unfortunately the Bind is not available in ASP.Net 2.0 instead Eval only is available. We could still achieve this in two simple and easy steps. 1. Wrap the Eval(fieldname) HTML code in a function eg: Checkvalue that checks the datafield value, performs transformations to True OR False values and assigns to Chekced property. 2. Override the RowUpdating event of gridview and update only the Checked property's value since the SQLDataSource that is bound to gridview will take care of remaining fields to update. Please let me know if this has helped anyone solve the problem!!

In this Article you can learn how to get a Selected Row Data from a DataList and display the data in textBoxes.

In this section we will learn about the basics of MVC and then see how we can implement the same in ASP.NET using HttpHandlers.

To generate Edit, Delete, Update and Select buttons automatically in the GridView, we can follow this approach.

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you found plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/21/2012 8:24:57 AM