Horizontal Menu Bar

Follow C# Tutorials

Thursday, 23 May 2013

C#.Net – XML serialization in C# VS 2010

In this c# tutorial we are going to learn xml serialization in c#.

Why we need a serialization? :

Well, the simple answer to this is – to persist an object and save it in a specified storage location like a physical file or DataBase.
C# xml serialization
XML serialization

Serialization converts an object into a stream and then uses it either to save it in a file or to send/transport over any communication channel. Serialization in c# is very easy because c# with .net framework has several c# serialization techniques. Few of them are listed below, however in this article we are going to focus on C# xml serialization technique only.


1) XML serialization
2) Binary serialization
3) SOAP serialization

What is C# XML serialization? :

As name suggests, a serialization technique in which an object will be converted/saved into xml format or stream. To use serialization in xml we need XmlSerializer class. This class is derived from System.Xml.Serialization. Serialize and Deserialize are the two most important methods that we use to serialize object to xml and then again deserialize into object.

Things to remember while using xml serialization and deserialization in c# -

1) Only public objects can be serialized in XML serialization. And hence it is called as Shallow serialization.
2) Classes inherited from IEnumerable and ICollection can also be serialized, however it serializes only collections and not public properties.
3) Private or read-only properties, Methods, Indexers cannot be serialized using this xml serialization.

Let see different scenarios to understand how c# serialize object to xml.

A. Basic Serialization ::

Let’s take a simple example. Take a look at below class –

public class BasicSerialization
{
   public String name = "C# Tutorials";
}

BasicSerialization is a class that has only public field "name" with defualt value "c# tutorial". Now use below code (method) to serialize above class –

private static void BasicSerializationMethod()
{
     // Create an instance of BasicSerialization class.
     BasicSerialization serializeObject = new BasicSerialization();
     // Create and instance of XmlSerializer class.
     XmlSerializer xmlSerializer = new XmlSerializer(typeof(BasicSerialization));
     // Create an instance of stream writer.
     TextWriter txtWriter = new StreamWriter(@"C:\Serialization Examples\BasicSerialization.xml");
nbsp;    // Serialize the instance of BasicSerialization
     xmlSerializer.Serialize(txtWriter, serializeObject);
     // Close the stream writer
     txtWriter.Close();
}

What we have done here -

i) First we have created an object of a class BasicSerialization, the object which we are going to serialize.
ii) Created an object of XmlSerializer of type BasicSerialization.This object will then be used to serialize.
iii) Created an object of Text StreamWriter to save file in physical location.
iv) Called “Serialize” method of xmlSerializer class to happen a xml serialization of above mentioned object.
v) Closed the TextWriter.

After serialization of an instance of above class, the xml at location highlighted above would look a like –

<?xml version="1.0" encoding="utf-8"?>
<BasicSerialization>
  <name>C# Tutorials</name>
</BasicSerialization>

Note: you might also get xml namespaces with root element.

B. Basic Serialization with more properties in class-

In this example, we are creating a new class “Camera” with two properties –

    public class Camera
    {
        public string MakeModel { get; set; }
        public string Price { get; set; }
    }

Now, serialize object of this class using following code –

private static void SerializationCamera()
{
     // Create an instance of Camera class.
     Camera camera = new Camera();
     // Assing values to it’s properties
     camera.MakeModel = "Canon EOS-1D";
     camera.Price = "$5219";
     // Create and instance of XmlSerializer class.
     XmlSerializer xmlSerializer = new XmlSerializer(typeof(Camera));
     // Create an instance of stream writer.
     TextWriter txtWriter = new StreamWriter(@"C:\Serialization Examples\BasicSerializationCamera.xml");
     // Serialize the instance of BasicSerialization
     xmlSerializer.Serialize(txtWriter, camera);
     // Close the stream writer
     txtWriter.Close();
}

Here we are serializing the same way as we did in first example. The output xml of this will be look a like –

<?xml version="1.0" encoding="utf-8"?>
<Camera xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
                  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <MakeModel>Canon EOS-1D</MakeModel>
  <Price>$5219</Price>
</Camera>

C. Serialization with XmlElement -

If you closely look at the xml file in above example, you will observe that the element names in xml file are same as property name in class definition. We can also define the element names with the use of XmlElement attribute. Look at below code, which is same as given above – only difference is that we used XmlElement with property definition –

public class Camera
{
  [XmlElement("CameraName")]
  public string MakeModel { get; set; }
  [XmlElement("CameraPrice")]
  public string Price { get; set; }
}

Now again call the SerializationCamera() Method to generate the XML file as below –

<?xml version="1.0" encoding="utf-8"?>
<Camera xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <CameraName>Canon EOS-1D</CameraName>
  <CameraPrice>$5219</CameraPrice>
</Camera>

Observe the element names here. MakeModel is saved as CameraName and Price is saved as CameraPrice.

D. Serialize an array of objects

To understand how to serialize an array of object, again take the same example of Camera class given above.

Use following method to Serialize the array of a Camera class.

private static void SerializationCameraObjects()
{
     //Create first instance of Camera class.
     Camera camera1 = new Camera();
     camera1.MakeModel = "Canon EOS-1D";
     camera1.Price = "$5219";

     //Create second instance of Camera class.
     Camera camera2 = new Camera();
     camera2.MakeModel = "Canon EOS-1D Mark IV";
     camera2.Price = "$5000";

     // Create an array of Camera
     Camera[] cameras = new Camera[2];
     cameras[0] = camera1;
     cameras[1] = camera2;

     // Create and instance of XmlSerializer class.
     XmlSerializer xmlSerializer = new XmlSerializer(typeof(Camera[]));
     // Create an instance of stream writer.

     TextWriter txtWriter = new StreamWriter(@"C:\Serialization Examples\SerializationArrayOfObj.xml");
     // Serialize the instance of BasicSerialization
     xmlSerializer.Serialize(txtWriter, cameras);
     // Close the stream writer
     txtWriter.Close();
}

Look at the highlighted part to understand what we have changed from last source code.

The output will look a like –

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfCamera xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Camera>
    <CameraName>Canon EOS-1D</CameraName>
    <CameraPrice>$5219</CameraPrice>
  </Camera>
  <Camera>
    <CameraName>Canon EOS-1D Mark IV</CameraName>
    <CameraPrice>$5000</CameraPrice>
  </Camera>
</ArrayOfCamera>

E. Serialize a DataSet

Let’s assume we have a dataset which has a DataTable with two columns and two rows. This DataSet stores CameraDetails as shown in below table –

Camera Make Model
Price
Canon EOS-1D
$5219
Canon EOS-1D Mark IV
$5000

We would use below method to serialize DataSet in xml –

private static void DataSetSerialization()
{
     // Create and instance of XmlSerializer class.
     XmlSerializer xmlSerializer = new XmlSerializer(typeof(DataSet));
     // Create a DataSet; adds a table, column, and ten rows.
     DataSet cameraDS = new DataSet("Camera");
     // Create DataTable.
     DataTable cameraDT = new DataTable("CameraDetails");
     // Specify columns of a DataTable
     cameraDT.Columns.Add("MakeModel"); //Column1
     cameraDT.Columns.Add("Price"); //Column2s
     // Add rows in DataTable
     cameraDT.Rows.Add("Canon EOS-1D", "$5219");
     cameraDT.Rows.Add("Canon EOS-1D Mark IV", "$5000");
     // Add DataTable in DataSet
     cameraDS.Tables.Add(cameraDT);
     // Create an instance of stream writer.
     TextWriter txtWriter = new StreamWriter(@"C:\Serialization Examples\DataSetSerialization.xml");
     // Serialize the instance of BasicSerialization
     xmlSerializer.Serialize(txtWriter, cameraDS);
     // Close the stream writer
     txtWriter.Close();
}

The output of above code will be like below xml –

<?xml version="1.0" encoding="utf-8"?>
<DataSet>
  <xs:schema id="Camera" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xs:element name="Camera" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
      <xs:complexType>
        <xs:choice minOccurs="0" maxOccurs="unbounded">
          <xs:element name="CameraDetails">
            <xs:complexType>
              <xs:sequence>
                <xs:element name="MakeModel" type="xs:string" minOccurs="0" />
                <xs:element name="Price" type="xs:string" minOccurs="0" />
              </xs:sequence>
            </xs:complexType>
          </xs:element>
        </xs:choice>
      </xs:complexType>
    </xs:element>
  </xs:schema>
  <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
    <Camera>
      <CameraDetails diffgr:id="CameraDetails1" msdata:rowOrder="0" diffgr:hasChanges="inserted">
        <MakeModel>Canon EOS-1D</MakeModel>
        <Price>$5219</Price>
      </CameraDetails>
      <CameraDetails diffgr:id="CameraDetails2" msdata:rowOrder="1" diffgr:hasChanges="inserted">
        <MakeModel>Canon EOS-1D Mark IV</MakeModel>
        <Price>$5000</Price>
      </CameraDetails>
    </Camera>
  </diffgr:diffgram>
</DataSet>

In this article we have learnt c# object serialization using xml serializer. I hope you enjoyed the article. If yes then please feel free to share the article on your favourite social media using below "Sharing is Caring" widget.

Check Sitemap for more articles.

Follow C# Tutorials