Click here to Skip to main content
15,888,277 members
Articles / General Programming
Tip/Trick

Convert XML into Object using XML serialization (Deserialize from XML)

Rate me:
Please Sign up or sign in to vote.
4.43/5 (6 votes)
10 May 2012CPOL1 min read 47.5K   5   1
XML Serialization

Introduction

In this tip, I’m explaining how we can convert XML into an object using XML Serialization.

Background

The same using LINQ is available in: http://www.codeproject.com/Tips/366993/Convert-XML-to-object-using-LINQ.

Using the code

For this example, I am using the following XML:

XML
<ArrayOfStudent>
  <Student>
    <Name>Name1</Name>
    <Batch>I</Batch>
    <School>11/7/1997</School>
    <marks>
      <mark>
        <term>I</term>
        <science>46</science>
        <mathematics>50</mathematics >
        <language>46</language>
        <result>Pass</result>
        <comments>
          <teacher>good</teacher>
          <parent></parent>
        </comments>
      </mark>
    </marks>
  </Student>
</ArrayOfStudent>

Here the XML format is fairly simple – need to convert this xml to a class object containing object array (for <marks> node) using XML Serialization

A brief explanation about this XML structure

From top node–

    How do we convert this to an object?

    It is really simple ... We start from bottom i.e., <comments>.

  • Each student has name, batch and school
  • Each student has multiple term marks (e.g.: First Term/Second Term etc..)
  • In each term there will be separate comment about student performance (teacher/parent)

Step I: Convert <comments> to a class:

XML
 <comments>
   <teacher>gooSDFSd</teacher>
   <parent></parent>
 </comments>

public class Comment
{
   [XmlElement("teacher")]
   public string TeacherComment { get; set; }
   [XmlElement("parent")]
   public string ParentComment { get; set; }
}

Tip: The XmlElement Attribute maps the property name with the XML node, i.e., the TeacherComment property maps with the XML node teacher.

Step II: Convert <mark> to class.

XML
<marks>
      <mark>
        <term>I</term>
        <science>46</science>
        <mathematics>50</mathematics >
        <language>46</language>
        <result>Pass</result>
        <comments>
          <teacher>good</teacher>
          <parent></parent>
        </comments>
      </mark>
</marks>
C#
[XmlType("mark")]
public class Mark
{
    [XmlElement("term")]
    public string Term { get; set; }
    [XmlElement("science")]
    public string Science { get; set; }
    [XmlElement("mathematics")]
    public string Mathematics { get; set; }
    [XmlElement("language")]
    public string Language { get; set; }
    [XmlElement("result")]
    public string Result { get; set; }
    [XmlElement("comments")]
    public Comment objComment = new Comment();
}

Here we bind Comment with in Mark class using as code below

C#
[XmlElement("comments")]
public Comment objComment = new Comment();

As I mentioned in top a student can have multiple marks based on the term/session. So we need to create List<T> of marks as below:

C#
[XmlArray("marks")]
public List<Mark> objMarkList = new List<Mark>(); 

Complete code looks like...

C#
 public class Student
{
    [XmlElement("Name")]
    public string StudentName { get; set; }
    [XmlElement("Batch")]
    public string Batch { get; set; }
    [XmlElement("School")]
    public string School { get; set; }
    [XmlArray("marks")]
    public List<Mark> objMarkList = new List<Mark>();
}

Now we have created Student class with Mark which contain Comment

Let’s move to Deserialization.

C#
XmlSerializer deserializer = new XmlSerializer(typeof(List<Student>));
TextReader textReader = new StreamReader(@"XML file path");
List<Student> stud;
stud = (List<Student>)deserializer.Deserialize(textReader);
textReader.Close();
foreach (var _stud in listStd)
{
   // Your code
}

What is happening here!!!

C#
XmlSerializer deserializer = new XmlSerializer(typeof(List<Student>)); 

XmlSerializer deserializes from a stream , so we create a file stream from our XML file ,

C#
TextReader textReader = new StreamReader(@"XML file path");

Then simply call Deserialize on the stream and cast the output to our desired type. Now the students list is populated with objects.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Member 233173325-Aug-16 0:45
Member 233173325-Aug-16 0:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.