Thursday, August 11, 2011

Serialization in .Net – Part-3 (XML Serialization with Example)

Serialization in .Net – Part-1 (What is Serialization)
Serialization in .Net – Part-2 (Binary Serialization with Example)
Serialization in .Net – Part-3 (XML Serialization with Example)
Serialization in .Net – Part-4 (SOAP Serialization with Example)
Serialization in .Net – Part-5 (Custom Serialization with Example)

XML Serialization:  (Interoperable use SOAP and used in web Services)

XML serialization allows the public properties and fields of an object to be reduced to an XML document that describes the publicly visible state of the object.
XML serialization serializes the public fields and properties of an object, or the parameters and return values of methods, into an XML stream that conforms to a specific XML Schema definition language (XSD) document. XML serialization results in strongly typed classes with public properties and fields that are converted to XML. System.Xml.Serialization contains the classes necessary for serializing and deserializing XML.
You can apply attributes to classes and class members in order to control the way the XmlSerializer serializes or deserializes an instance of the class.
  • Serializes and object in XML format.

  • Requeriments:
    • Type must be public (public class person)

    • Must implement a parameterless constructor (in order to deserialize the object)

    • If you are serializing a non generic collection of items, you must pass the types that are stored in the collection as a parameter in the constructor of the XmlSerializer (see example code).


PROS
  • It can serialize generic and non generic collections (being the items within the collection serializable)

  • Class doesn't need to be decorated with [Serializable] attribute.

  • Developer has a deep control about how each field is going to be serialized by using the attributes:
    • [XmlAttribute] : over a field, marks that the field will be serialized as attribute, instead of a node

    • [XmlIgnore] : won't serialize that field. The same as NonSerializable, but just for the XmlSerializer.

    • [XmlElement (ElementName="NewName"]: Allows you to rename the field when being serialized.


CONS
  • Only public members will be serialize! (shallow serialization) (both BinaryFormatter and SoapFormatter would serialize also object private members)



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization; //<-- Namespace for Custom Serialization
                                    //(ISerializable,SerializationInfo,StreamingContext)
using System.Runtime.Serialization.Formatters.Binary;//<-- Namespace for Binary Serialization
using System.Xml.Serialization;//<-- Namespace for XML Serialization
using System.Runtime.Serialization.Formatters.Soap;//<--Namespace for Soap Serialization


namespace XMLSerializationByManishAgrahari
{
    [Serializable]//<-- This atribute is just required by BinaryFormatter and SoapFormatter
    public class Employee//<-- XMLSerializer needs that the class is defined as public 
    {
        public int id;
        public string name;//<-- public properties to serialize. They  will be serialize by the three formatters. 
        private string address;//<--this private field won't be serialized using XmlSerialization.
        //They will be serialized using Binary or Soap formatters 
        [NonSerialized] //<-- Using this attribute, the field "gender"
                        //won't be serialized (by any of the three
serializers)
//When using the BinaryFormatter or SoapFormatter classes to serialize an object,
//use the [NonSerialized] Attribute attribute to prevent a field from being serialized.

        public string gender;
        //let's create a method to set the private properties. 
        public void SetAddress(string address)
        {
            this.address = address;
        }

        public string GetAddress()
        {
            return this.address;
        }
    }

    class TestSerialization
    {

        public void XMLSerialize( String filename, Employee emp)
        {
            XmlSerializer serializer = null;
            FileStream stream = null;
            try
            {
                serializer = new XmlSerializer(typeof(Employee));
                stream = new FileStream(filename, FileMode.Create, FileAccess.Write);
                serializer.Serialize(stream, emp);
            }
            finally
            {
                if (stream != null)
                    stream.Close();
            }
        }

        public Object XMLDeserialize(String filename)
        {
            XmlSerializer serializer = null;
            FileStream stream = null;
            Employee emp = new Employee();
            try
            {
                serializer = new XmlSerializer(typeof(Employee));
                stream = new FileStream(filename, FileMode.Open);
                emp = (Employee)serializer.Deserialize(stream);
            }
            finally
            {
                if (stream != null)
                    stream.Close();
            }
            return emp;
        }


        public static void Main()
        {
            Console.WriteLine("*********  XML Serialization *********");
            String file = @"C:\\XML_Serialization.xml";
            Employee objEmp = new Employee();
            objEmp.id = 1001;
            objEmp.name = "Manish Agrahari";
            objEmp.SetAddress("Noida");
            objEmp.gender = "Male";

            // Serializataion
            TestSerialization objTestSerialization = new TestSerialization();
            objTestSerialization.XMLSerialize(file, objEmp);
            Console.WriteLine("Object Saved on Location: " + file);

            // Deserialization
            Employee objEmployee = (Employee)objTestSerialization.XMLDeserialize(file);
            Console.WriteLine("*********  After Deserialization *********");
            Console.WriteLine("Employee ID: " + objEmployee.id);
            Console.WriteLine("Employee Name: " + objEmployee.name);
            Console.WriteLine("Employee Address: " + objEmployee.GetAddress());
            Console.WriteLine("Employee Gender: " + objEmployee.gender); //<-- Here Gender will be blank during deserialization
            //Because It could not be serialized due to [NonSerialized] Attrubute
            Console.ReadLine();


        }
    }
}



 

- <Employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
         <id>1001id>
       <name>Manish Agrahariname>
         <gender>Malegender>
  Employee>

When using the BinaryFormatter or SOAPFormatter classes to serialize an object, use the NonSerializedAttribute attribute to prevent a field from being serialized.

If you are using the XMLSerializer class to serialize an object, use the XMLIgnoreAttribute class to get the same functionality.      

  Note: - In above example you can see field gender also serialized when using XMLSerializer. So that [NonSerialized] attribute does not work with XMLSerializer.

0 comments: