May
22
2013

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

In this c# tutorial we are going to learn xml serialization in c#. Before we start how to achieve xml serialization in c#, lets understand what is Serialization?

What is Serialization and why do 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.

XML Serialization in C#.Net
XML Serialization in C#.Net

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 XML serialization in C#.Net?

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 also 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.

Vice versa of XML serialization is called as XML deserialization. In XML serialization the object gets converted into xml stream/file, and converting that xml stream/file to an object again is called as XML Deserialization. XML Serialization and DeSerialization in C# are the most important topics in .Net.

How to do XML Serialization?

There are many ways c# serialize object to xml. This articles covers following ways of XML serialization.

  1. XML Serialization of simple class object : Serialize the object into XML as it is.
  2. XML Serialization of a Class object containing many properties : Serialize the object into XML as it is.
  3. XML Serialization using XMLElement : Control the name of properties using XMLElement in XML serialization. You can specify an alternate name for properties of an object to save into XML.
  4. XML Serialization of array of Objects : Serialize the array of objects into XML.
  5. XML Serialization of DataSet : Serialize a DataSet into XML.

A. XML Serialization of simple class object

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

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

Here 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.
     TextWritertxtWriter = new StreamWriter(@”C:Serialization ExamplesBasicSerialization.xml);
nbsp;    // Serialize the instance of BasicSerialization
     xmlSerializer.Serialize(txtWriter, serializeObject);
     // Close the stream writer
     txtWriter.Close();
}

What we have done here –

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

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

<?xmlversion=1.0encoding=utf-8?>
<BasicSerialization>
  <name>C# Tutorials</name>
</BasicSerialization>

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

B. XML Serialization of a Class object containing many properties.

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 = newCamera();
     // 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 = newStreamWriter(@”C:Serialization ExamplesBasicSerializationCamera.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 –

<?xmlversion=1.0encoding=utf-8?>
<Cameraxmlns: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. XML Serialization using XMLElement

If you closely look at the output 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.

Now, 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 –

<?xmlversion=1.0encoding=utf-8?>
<Cameraxmlns: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. XML Serialization of 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 = newCamera();
     camera1.MakeModel = “Canon EOS-1D”;
     camera1.Price = “$5219”;

     //Create second instance of Camera class.
     Camera camera2 = newCamera();
     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 = newStreamWriter(@”C:Serialization ExamplesSerializationArrayOfObj.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 –

<?xmlversion=1.0encoding=utf-8?>

<ArrayOfCameraxmlns:xsi=http://www.w3.org/2001/XMLSchema-instancexmlns: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. XML Serialization of 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

To serialize a DataSet in xml we would use below method –

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 = newDataSet(“Camera”);
     // Create DataTable.
     DataTable cameraDT = newDataTable(“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 = newStreamWriter(@”C:Serialization ExamplesDataSetSerialization.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 –

<?xmlversion=1.0encoding=utf-8?>

<DataSet>
  <xs:schemaid=Cameraxmlns=“”xmlns:xs=http://www.w3.org/2001/XMLSchemaxmlns:msdata=urn:schemas-microsoft-com:xml-msdata>
    <xs:elementname=Cameramsdata:IsDataSet=truemsdata:UseCurrentLocale=true>
      <xs:complexType>
        <xs:choiceminOccurs=0maxOccurs=unbounded>
          <xs:elementname=CameraDetails>
            <xs:complexType>
              <xs:sequence>
                <xs:elementname=MakeModeltype=xs:stringminOccurs=0 />
                <xs:elementname=Pricetype=xs:stringminOccurs=0 />
              </xs:sequence>
            </xs:complexType>
          </xs:element>
        </xs:choice>
      </xs:complexType>
    </xs:element>
  </xs:schema>
  <diffgr:diffgramxmlns:msdata=urn:schemas-microsoft-com:xml-msdataxmlns:diffgr=urn:schemas-microsoft-com:xml-diffgram-v1>
    <Camera>
      <CameraDetailsdiffgr:id=CameraDetails1msdata:rowOrder=0diffgr:hasChanges=inserted>
        <MakeModel>Canon EOS-1D</MakeModel>
        <Price>$5219</Price>
      </CameraDetails>
      <CameraDetailsdiffgr:id=CameraDetails2msdata:rowOrder=1diffgr: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. Please read next topic on how to Deserialize XML into an object.

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.

More articles –

About the Author: Ashish Ramteke

Ashish Ramteke is a Software Professional, Part time blogger and founder of C# Tutorials, a popular blog on C#.Net. Ashish is having 6 years of work experience and an engineering degree in Computer Science and Engg.

1 Comment+ Add Comment

Leave a comment