Saturday, 9 November 2013

XML Serialization in c#

According to MSDN definition "Serialization is the process of converting an object into a stream of bytes in order to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization".

After serialization data can be stored into a file,database,memory etc. This is simple three step process:

First step is to create a class which's object you want to serialize into xml file i.e.

public class Movie
    {
        // Default ctor
        public Movie()
        { 

        }
        [XmlAttribute(AttributeName="MovieTitle")]  // stores element in xml file with this name
        public string Title
        {
            get;
            set;
        }
        public string Director
        {
            get;
            set;
        }
        [XmlElement(ElementName ="ReleaseDate")]
        public DateTime Year
        {
            get;
            set;
        }
        public double Budget
        {
            get;
            set;
        }
    }
Where  [XmlElement(ElementName ="ReleaseDate")] is used to change the name of the property on run time and save this property in xml file with new name.

Second step is to write a function which will be used to serialize above class's object into xml. i.e.

 private static void SerializeMovieXML(List<Movie> movies)
        {
            // Step 1
            XmlSerializer serializer = new XmlSerializer(typeof (List<Movie>));
            // Step 2
            TextWriter txtWriter = new StreamWriter(@"D:\Movies.xml");
            // Step 3
            serializer.Serialize(txtWriter, movies);
            // step 4
            txtWriter.Close();
        }
This function store Movies.xml file in D drive , you can change this location.

Third step is to create object of movie class and use above method to create xml.

 Movie m = new Movie();

            m.Title = "BOL";
            m.Director = "Shoiab Mansoor";
            m.Year = new DateTime(2011, 09, 05);
            m.Budget = 10000000;


            Movie m1 = new Movie();

            m1.Title = "Forrest Gump";
            m1.Director = "I Dont Know";
            m1.Year = new DateTime(1990, 09, 05);
            m1.Budget = 50000000;

            List<Movie> movie = new List<Movie>();

            movie.Add(m);
            movie.Add(m1);



            SerializeMovieXML(movie);

In result of above code , this xml will be produce in Movies.xml file.

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfMovie xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Movie MovieTitle="BOL">
    <Director>Shoiab Mansoor</Director>
    <ReleaseDate>2011-09-05T00:00:00</ReleaseDate>
    <Budget>10000000</Budget>
  </Movie>
  <Movie MovieTitle="Forrest Gump">
    <Director>I Dont Know</Director>
    <ReleaseDate>1990-09-05T00:00:00</ReleaseDate>
    <Budget>50000000</Budget>
  </Movie>
</ArrayOfMovie>

Now if you want to de-serialize above xml into object , following method will be used :
   private static List<Movie> DeserializeMovieXML()
        {
            // step 1
            XmlSerializer serializer = new XmlSerializer(typeof (List<Movie>));
            // step 2
            TextReader txtReader = new StreamReader(@"D:\Movies.xml");
            // step 3

            List<Movie> m = serializer.Deserialize(txtReader) as List<Movie>;

            txtReader.Close();

            return m;
        }
and you can use this method in this way to get your object back :

            List<Movie> movies = DeserializeMovieXML();
That's it, do code and enjoy :)