Please navigate to the bottom of the page for Table of Contents

Wednesday, May 25, 2011

How do you serialize an object to and from XML

Technorati Tags: ,,,

For an ASP.NET object to be saved in a session, it needs to be serialized (not entirely correct – in proc session state allows objects to be non-serializable). Some other use cases are when you want to send and receive objects over the wire (web services) or when you perhaps want to save them to Isolated Storage (Windows Phone 7). The basic question is: How do you enable serialization/ de-serialization of .NET objects?

The answer is to use the XmlSerializer class. There are certain restrictions on the objects that can serialized to and from XML. Before we discuss those properties, let's explore the basic functions to serialize/de-serialize any object:

using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;

namespace SimpleCodingQuestions
class SerializationHelper
/// <summary>
/// Serializes the given object data to string representation
/// </summary>
/// <param name="dataToSerialize">the object data to serialize</param>
/// <param name="objectType">the object class type</param>
/// <returns>a string representation for demo purposes</returns>
public static string Serialize(object dataToSerialize, Type objectType)
string objAsString = null;
// instantiate an XmlSerializer class
XmlSerializer xs = new XmlSerializer(objectType);
// for the purpose of explaining,
// we will be writing to a string
// in real world, this might be writing to a file
StringBuilder sb = new StringBuilder();
// wrap the serialization
using (StringWriter sw = new StringWriter(sb))
// now serialize the data
xs.Serialize(sw, dataToSerialize);

return objAsString;

As you can see from the program above, you first create an XmlSerializer object with the typeof object you want to serialize. Then you simply call the Serialize method on it.


Now let's review the de-serialization code. It is very similar to the above code.


public static object Serialize(string serializedData, Type objectType)
object returnObj = null;
// instantiate an XmlSerializer class
XmlSerializer xs = new XmlSerializer(objectType);
// wrap the serialization
using (StringReader sr = new StringReader(serializedData))
// now de-serialize the data
returnObj = xs.Deserialize(sr);

return returnObj;


So, what are the restrictions on the objects that can be serialized to and from XML?

  • Only public types and public data members will be used.

  • The class needs to provide a no-arg (parameterless) constructor.

  • If the class is made up of complex objects, only public types of those types will be serialized

How can you modify/control the XML that is being generated by XmlSerializer?

Although the process of XML generation is straightforward, .NET framework provides you with many ways to customize the output. You can control the generation by using attributes that can decorate the public types and properties. A few examples are:

  • Use [XmlIgnore] attribute to exclude a certain property from being serialized

  • Use [XmlElement("DifferentElementName")] to rename a property to another name in the generated XML.

  • Use [XmlAttribute("DifferentNameAsAttribute")] to rename a property to another name in the generated XML and also to serialize it as an attribute of the XmlElement as compared to a sub element of the main element.

There are many other properties and attributes that can be configured for an XmlSerializer, making it a very powerful and versatile tool for a developer.





  1. When some one searches for his essential thing, therefore he/she
    wishes to be available that in detail, ... Sewa Mobil Surabaya Admiring the effort and time you put into your site and in depth information you present.
    Rental Mobil Yogyakarta It’s good to come across a blog every every now and then that isn’t the same old rehashed information.
    Sewa Mobil Makassar Fantastic post! so that thing is maintained over here.

  2. Halo,

    Nice to be visiting your blog again, it has been months for me. Well this article that i’ve been waited for so long.

    I found this primMST java class source code online for the prim algorithm. It was accompanied by another class called BinaryMinHeap, which is used in the primMST class. I copied and pasted the primMST code in NetBeans, and it gave me error labels in the text editor for three classes that were used in the primMST class. They are class Edge, Graph, and Vertex.

    There was another error for class List, but I fixed that by using the import statement import java.util.*;

    Is there an import statement for the class called "Edge", "Graph", and "Vertex"? I've been searching google but I couldn't find anything. Below is the source code for primMST class.
    It was cool to see your article pop up in my google search for the
    yesterday. Great Guide.
    Keep up the good work!


  3. design agency
    Remarkable blog! I have no words to praise, it has really allured me.

  4. There are multiple methods of paying for your exposition at edubirdie. Use your mastercard, use paypal prospects, or make the pay someone to write my assignment cycle simpler by downloading our iphone application. Note that the last total will be extricated just once the essayist presents their work.

  5. If you're in need of foundation repair Edmonton, then look no further than Rammafoundation - the foundation repair experts. We understand just how important it is to have your foundations looking their best, and we'll be there to help you get back to your pre-existing level of confidence and attractiveness. Our team of skilled and experienced specialists will work hard to get the job done quickly and efficiently, so you can move on with your life without any worries about your skin's integrity. Contact us today for a consultation!