Resources » .NET programming » .NET Framework

XML serialization and Binary serialization


Posted Date: 22-May-2004  Last Updated:   Category: .NET Framework    
Author: Member Level: Gold    Points: 10


This article explains what is serialization, difference between xml serialization and binary serialization and provides a sample project which demonstrates the serialization features in .NET



What is serialization?

Serialization is the process of saving the current state of any object into persistent storage (like file system), so that it can be retrieved later (Deserialize) and re create the same object.

For example, you have an object called student. You assign some values into the properties of this student object and serialze this object into a file. You can keep this file and de serialize any time later to re produce your student to the saved state.

What is serializable class ?

If a class can be serialized by using the builtin serialization features in .NET, that class is called serializable class. Most of the classes provided by .NET Framework is serializable.

Different types of Serialization

There are two broad categories of serialization in .NET

1. XML Serialization
2. Binary Serialization

XML Serialization serializes the object into an xml file. This file is human readable and can be shared with other applications.

Binary serialization is more efficient, but the serialized file is in binary format. It may not make any sense for a human being to open this file and understand what it contains. It is a stream of bytes.

Can I make my own classes serializable ?

Yes, it is very easy to make any class serializable. Simply add an attribute called 'Serializable' just above the class declaration and your class is serializable - means anybody can write few lines of C# code to save the state of the instance of your class into disk and retrieve (deserialize) later.

[Serializable]
public class MyClass
{
public string name;
public string adress;
}

How to serialize classes ?

The following samples demonstrate how to do XML Serialization and Binary Serialization using .NET classes.

We are serializing an 'ArrayList' object into disk and deserializing it again from the disk into another array list.

If you are not familiar with ArrayList - it is a collection class provided by .NET Framework, which can hold a list of any objects. The sample shown below uses an ArrayList which holds a list of strings.

XML Serialization

ArrayList itemsToSerialize = new ArrayList();
itemsToSerialize.Add ( "john" );
itemsToSerialize.Add ( "smith" );

XmlSerializer serializer = new XmlSerializer( typeof(ArrayList) );

TextWriter writer = new StreamWriter( @"MyApplicationData.xml" );
serializer.Serialize( writer, itemsToSerialize );
writer.Close();

In the first step, we are creating an array list and adding two strings into it. next step is to create an instance of XmlSerializer class, which is provided by .NET Framework to help serialize any objects. In the constructor of XmlSerializer class, we have to specify what type of object we want to serialize using this. Since we are going to serialize an ArrayList, we are specifying 'typeof(ArrayList)'.

Next, we are going to do the real thing - saving the state of the ArrayList into an XML file. We will create a TextWriter object and specify the xml file name to which we will save the ArrayList.

The following lines will save the arraylist 'itemsToSerialize' into the file 'MyApplicationData.xml':

TextWriter writer = new StreamWriter( @"MyApplicationData.xml" );
serializer.Serialize( writer, itemsToSerialize );
writer.Close();

Now, you can check the folder where your application executable is. A file with the name 'MyApplicationData.xml' will be created and you can open the file in any text editor to see the content.

Deserialization

We have serialized an arraylist into an xml file. This means, the state of the arraylist is saved into the xml file. So, we should be able to retrieve the same arraylist from this xml file. The following code will deserialize the arraylist from the xml file.

Stream stream = new FileStream( @"MyApplicationData.dat", System.IO.FileMode.Open );

IFormatter formatter = new BinaryFormatter();
ArrayList itemsDeserialized = (ArrayList)formatter.Deserialize( stream );

stream.Close();

Just few lines of code ! The above code will read the XML file 'MyApplicationData.dat' and restore the arraylist 'itemsDeserialized' - means the list of items we originally saved into the XML file will be loaded back to the array list. Now the arraylist 'itemsDeserialized' will contain two strings 'john' 7 'smith' whcih we saved as part of the serialization process.

Binary Serialization

Binary serialization is pretty much same as XML serialization, except that the data stored in a stream of bytes, not in XML format. See the sample code :

ArrayList itemsToSerialize = new ArrayList();
itemsToSerialize.Add ( "john" );
itemsToSerialize.Add ( "smith" );

Stream stream = new FileStream( @"MyApplicationData.dat", System.IO.FileMode.Create );
IFormatter formatter = new BinaryFormatter();
formatter.Serialize( stream, itemsToSerialize );

stream.Close();

The above code sample will serialize the arraylist 'itemsToSerialize' into the file 'MyApplicationData.dat'.

Deserializing the binary data

The objects serialized using binary formatter can be deserialized the same way.

Stream stream = new FileStream( @"MyApplicationData.dat", System.IO.FileMode.Open );

IFormatter formatter = new BinaryFormatter();
ArrayList itemsDeserialized = (ArrayList)formatter.Deserialize( stream );

stream.Close();

The above sample will read the file 'MyApplicationData.dat' and restore the arraylist 'itemsDeserialized'.

Where is Serialization used

Serialization has lot of uses in application development. One important purpose is to transmit data between application domains. Webservices and remoting uses serialization/deserialization technique to exchange data.

When you call a webservice and pass parameters, the parameters are serialized into XML data and send to the server. When the webservice return data, the result is serialized into XML and returned to the caller. This means, you can pass only serializable data in web service calls.

In Remoting, you can choose either Binary or SOAP(XML) formatting. Depending on what format you choose, data is serialized using xml or binary format and exchanged between the server and client.

In addition to the above, you can use serialization as a way to store the application data into files. For example, you want to save the last logged in user name, but you don't have a database. You can serialize the user object itself or serialize just the name of the user into disk. When you start the application next time, you can deserialize the user name from the serialized data. Many of the applications use this serialization mechanism to remember the user settings and application data.

Summary

The classes provided by .NET Framework make it very easy to persist the state of any serializable object and restore it to the same state. In the above samples, we have used an ArrayList object. Instead of ArrayList, we can serialize/de serialize any serializable objects including custom classes.

Sample Application

The attached sample application demonstrates both XMl serialization and Binary serialization. The sample project has a list box. You can add/remove items to the listbox. When you press the serialize button, the items in the listbox is copied to an ArrayList object and this array list is serialized.



When you press the de serialize button, the data is de serialzed into an Arraylist object and the listbox is loaded from this array list.

Note that the data serialized will persist even after you close the application. So, you can add few items into the list box in the sample project, serialize them into file and close the application. When you re start the application, you can restore the state of your list box you saved last.

Download sample application


Did you like this resource? Share it with your friends and show your love!

Responses to "XML serialization and Binary serialization"
Author: Janak Ram    03 Jul 2004Member Level: Bronze   Points : 0
Very good article by Tony. All these artciles become more useful to fellow programmers only when they are provided with samples or proper explanations.

Tony did a wonderful job here.



Author: Astrix The Gaul    15 Sep 2004Member Level: Bronze   Points : 0
Great article tony ..


Author: Rakesh Chander Sharma    21 Oct 2004Member Level: Silver   Points : 0
Very nice article tony, i think the simplicity of the article would make it easily understandable for all .
Nice Work



Author: LeninGrad    28 Jan 2005Member Level: Silver   Points : 0
Hai Tony,

Your explanation about XML and Binary serialization was superb. I could not imagine whether I could get better explanation than this. Thanx a lot for ur explanation.



Author: Madhusudhan    05 May 2008Member Level: Bronze   Points : 2
This article is very nice however my dought is that Is the process of deserialization in both XML and binary is same?
And friends pls let me know who and how will i get the reply pls



Author: Deshi    15 Dec 2008Member Level: Silver   Points : 0
Hi Tony,

great article, easy to understand.



Author: rajesh kumar parbat    03 Jun 2010Member Level: Gold   Points : 0
Nice Article


Author: Navin C Pandit    30 Jul 2010Member Level: Gold   Points : 1
Hi Tony,
Good article & really very understandable. Many thanks for sharing with us, keep it up. But where file "MyApplicationData.dat" will be stored as you mentioned the path?
It will store it into 'C:\Program Files\Microsoft Visual Studio 8\Common7\IDE'

Thanks,
Navin



Feedbacks      

Post Comment:




  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:   Sign In to fill automatically.
    Email: (Will not be published, but required to validate comment)



    Type the numbers and letters shown on the left.


    Submit Article     Return to Article Index

    Subscribe to Subscribers
    Active Members
    TodayLast 7 Daysmore...

    Awards & Gifts
    Talk to Webmaster Tony John

    Online Members

    Ram Prasad
    More...
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India