Friday, June 21, 2013

XML Serialization in C#

XML Serialization

XML Serialization serialize only public fields, properties of an object and parameters and return value of a method. That is why it is called Shallow Serialization.  XML serialization results in strongly typed classes with public properties and fields that are converted to XML. System.Xml.Serialization has all the classes and method need for XML serialization.
 

Example

The bellow example serialize a string array using XML Serialization and store it to a XML file. And again deserialize  from that xml file to a string array.



using System;
using System.IO;
using System.Xml.Serialization;
namespace Example_Serialization
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Serializing a string array and store it in country.xml");
            string[] country = new string[] { "India", "USA", "UK", "Australia" };
            XmlSerializer serialize = new XmlSerializer(typeof(string[]));
            StreamWriter writer = new StreamWriter("country.xml");
            serialize.Serialize(writer, country);
            writer.Close();

            Console.WriteLine("Deserializing a string array from country.xml");
            country = null;
            using (Stream streamload = new FileStream("Country.xml", FileMode.Open))
            {
                country = (string[])serialize.Deserialize(streamload);
                foreach (var str in country)
                {
                    Console.WriteLine("{0}", str);
                }
            }
            Console.ReadKey();
        }
    }
}