Jun
7
2013

C#.Net – XML DeSerialization in C#

In this article we will learn xml deserialization in c#. We have already learn how to work with xml serialization in c# in last article. The article explained what is Serialization? and Why do we need xml serialization? The article also covered few coding snippets/examples to c# serialize object in xml using c# xml serialization. If you are new to serialization or you need more information about xml serialization, then I would suggest you to refer xml serialization article.

XML Deserialization in C#.Net
XML Deserialization in C#.Net

What is De-Serialization?

From previous article we know that Serialization is the process of converting an object into a stream so that it can be saved in any physical file like (XML) or can be saved in Database. The main purpose of Serialization in C# is to persist an object and save it in any specified storage medium like stream, physical file or DataBase. Deserialization is vice-versa of Serialization.

Deserialization is the opposite process of serizalization in which the outcome of Serialization is again converted back into an original object.

What is XML DeSerialization?

The process of converting an XML into an object instance is known as XML Deserialization. To use deserialization in xml we need XmlSerializer class. This class is derived from System.Xml.Serialization. Two most important methods of this class are Serialize and Deserialize. These two methods are used to serialize object to xml and then again deserialize into object.

How to do XML DeSerialization in C#.Net?

So in this c# tutorial let’s learn how to deserialize xml into an object i.e. to read xml document and make an object from it. One thing we have learnt from XML serialization that – an object can be converted to xml schema and can be stored as a physical xml file. XML deserialization is a process in which we programmatically read that xml document and creates new object from that xml schema.

There are many ways c# serialize object to xml, so the xml Deserialization. This articles covers following ways of XML deserialization.

  1. DeSerialization of XML into simple class object : DeSerialize a simple XML into a simple object instance of a class.
  2. DeSerialization of XML containing many properties into a Class object : DeSerialize XML into an object instance of a class containing more properties.
  3. DeSerialization of XML containing XMLElement : We can 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 in serialization. Deserialize such XML into an object instance again.
  4. DeSerialization of XML into an array of Objects : DeSerialize XML of type arrays into the array of objects.
  5. DeSerialization of XML into a DataSet : DeSerialize a XML back into a DataSet.

Note: The examples of xml file used below are the outcome of XML serialization from previous article. Please refer XML serialization article to undesrtand how to generate below xml files.

A. DeSerialization of XML into simple class object

Consider below class –

public class BasicSerialization

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

Below xml schema shows how a single object of above class is serialized in xml file.

<?xmlversion=1.0encoding=utf-8?>
<BasicSerializationxmlns:xsi=http://www.w3.org/2001/XMLSchema-instancexmlns:xsd=http://www.w3.org/2001/XMLSchema>
  <name>C# Tutorials</name>
</BasicSerialization>

Hence, to deserialize above xml file you can use below DeSerialization code (method) –

private static voidBasicDeSerializationMethod()
{
     // Create an instance of BasicSerialization class.
     BasicSerializationserializeObject = new BasicSerialization();
     // Create an instance of new TextReader.
     TextReadertxtReader = new StreamReader(@”C:Serialization ExamplesBasicSerialization.xml”);
     // Create and instance of XmlSerializer class.
     XmlSerializerxmlSerializer = new XmlSerializer(typeof(BasicSerialization));
     // Deserialize from the StreamReader.
     serializeObject = (BasicSerialization)xmlSerializer.Deserialize(txtReader);
     // Close the stream reader
     txtReader.Close();
}

B. DeSerialization of XML containing many properties into a Class object

For example you have below class –

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

XML serialization of above class will give you following xml –

<?xmlversion=1.0encoding=utf-8?>
<Cameraxmlns:xsi=http://www.w3.org/2001/XMLSchema-instancexmlns:xsd=http://www.w3.org/2001/XMLSchema>
  <MakeModel>Canon EOS-1D</MakeModel>
  <Price>$5219</Price>
</Camera>
Following code can be used to convert above xml into an object instance –

private static voidDeSerializationCamera()
{
   // Create an instance of Camera class.
   Cameracamera = new Camera();
   // Create an instance of stream writer.
   TextReadertxtReader = new StreamReader(@”C:Serialization ExamplesBasicSerializationCamera.xml”);
   // Create and instance of XmlSerializer class.
   XmlSerializerxmlSerializer = new XmlSerializer(typeof(Camera));
   // DeSerialize from the StreamReader
   camera = (Camera) xmlSerializer.Deserialize(txtReader);
   // Close the stream reader
   txtReader.Close();
}

C. DeSerialization of XML containing XMLElement

Suppose you have a class with xmlelement attributes like below –

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

And you have serialized xml of above class like below –

<?xmlversion=1.0encoding=utf-8?>
<Cameraxmlns:xsi=http://www.w3.org/2001/XMLSchema-instancexmlns:xsd=http://www.w3.org/2001/XMLSchema>
 <CameraName>Canon EOS-1D</CameraName>
  <CameraPrice>$5219</CameraPrice>
</Camera>

In this case also you can use DeSerializationCamera() given in example B.

D. DeSerialization of XML into an array of Objects

Again here we are taking the example of above camera class. However look at below xml file, it shows multiple camera (nodes) objects instead single camera node –

<?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>

As above xml file includes multiple nodes (objects) of Camera types, to deserialize above xml file we need to modify above DeSerializationCamera() methods as follows –

private static void DeSerializationCameraMultipleObjects()
{
      // Create an instance of Camera class.
      Camera[] camera;
      // Create an instance of stream writer.
      TextReadertxtReader = new StreamReader(@”C:Serialization ExamplesSerializationArrayOfObj.xml”);
      // Create and instance of XmlSerializer class.
      XmlSerializerxmlSerializer = new XmlSerializer(typeof(Camera[]));
      // DeSerialize from the StreamReader
      camera = (Camera[])xmlSerializer.Deserialize(txtReader);
      // Close the stream reader
      txtReader.Close();
}

The highlighted part shows how the original method updated to get the array of same objects from xml file.

E. DeSerialization of XML into a DataSet

To get an xml into DataSet you don’t need XMLSerializer class and it’s DeSerialize() method. For example if you have already serialized your DataSet into xml file like below xml file –

<?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 case you actually don’t need DeSerialize() method. Use following code to get above xml in Dataset.

private static voidDeSerializationToDataSet()
{
    DataSetdeSerializeDS = new DataSet();
    try
    {
       deSerializeDS.ReadXmlSchema(@”C:Serialization ExamplesDataSetSerialization.xml”);
       deSerializeDS.ReadXml(@”C:Serialization ExamplesDataSetSerialization.xml”, XmlReadMode.IgnoreSchema);
    }
    catch (Exception ex)
    {
       // Handle Exceptions Here…..
    }
}

I hope this article helped you to understand how to deserialize xml into an object. 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.

9 Comments+ Add Comment

  • Nice post very helpful

    dbakings

  • Nice post very helpful

    dbakings

  • Nice. Thanks.

  • Hi, Nice demo about Xml DeSerialization in xml.Thanks….

    -Hari
    Theosoft

  • nicely explained

  • nice article.

  • thumbs up!!

  • Hello,
    D. DeSerialization of XML into an array of Objects
    as per your explanation the method is not working.
    It exit with the error “There is an error in xml document (2,2)”

  • good

Leave a comment