C#

Deserialize XML to Object C#

This post is about Deserialization of XML to the C# class object. Many a times, in coding we need to convert class to an XML and XML to a class object in our projects.

Here we will see in detail about how C# deserialize xml file or xml string with samples.

C# Deserialize XML

Below examples show reading the data stored in an XML file to a class object. Here Deserialize method from the XmlSerializer class is used for reading/deserializing the XML file data to the class object.

If you are looking for assistance to Deserialize XmlDocument to object C# or Parse XML to class C# this post will be very helpful.

Deserialize XML to Object C# – Example

In this example, we will Deserialize the XML file Department.xml into a C# object of class Department.

Consider the below XML file to Convert to C# Object 

<?xml version="1.0" encoding="UTF-8"?> 
<Department> 
    <Name>Mohan</Name> 
    <Location>Delhi</Location> 
    <Phone>9988774499</Phone> 
</Department>

Code Snippet: Read Data from an XML File to a Class in C# – Deserialize XML to object C#

/* Method to Deserialize the XML file.The method which creates 
   an object and deserializes the XML data to the object. */
internal Department DeserializeTheObject() 
{ 
    Department objectToDeserialize = new Department(); 
    XmlSerializer xmlserializer = new System.Xml.Serialization.XmlSerializer(objectToDeserialize.GetType()); 
 
   //Use using so that streamReader object will be cleaned up properly after use. 
   using(StreamReader streamReader = new StreamReader("D:\\Department.xml")) 
   { 
     return (Department)xmlserializer.Deserialize(streamReader); 
   }
}
/// The Employee class whose object will be serialized 

internal class Department 
{ 
    public string Name { get; set; } 
    public string Location { get; set; } 
    public string Phone { get; set; } 
}

Usage:

Call the Deserialize Object method from desired code location.I called it from a button click event in my form as below.
Deserialized data displayed using a message box.

private void button1_Click(object sender, EventArgs e)
{ 
   Deaprtment dept = DeserializeTheObject(); 
   MessageBox.show (", Department Name: "+ dept.Name + ", Location :"+ dept.Location + ", Phone : "+dept.Phone) 
}

Deserialization of Complex XML to Object C#

In this example, we will check how we can deserialize complete XML files into C# objects. When we say complex XML it is XMLs with deep nesting inside. Let’s see the sample of Deserializing nested xml into C# objects

We have a complex nested xml file (worldinfo.xml) as below

<?xml version="1.0" encoding="UTF-8"?>
<Countries> 
    <Country> 
         <State> 
            <Cities>
               <City> Impacted Population... </City> 
             </Cities>
         </State> 
    </Country> 
    <Country> 
         <State> 
            <Cities>
               <City> Impacted Population... </City> 
             </Cities>
         </State> 
    </Country> 
    <Country> 
         <State> 
            <Cities>
               <City> Impacted Population... </City> 
             </Cities>
         </State> 
    </Country> 
 ... 
</Countries>

Then need to have the following class hierarchy to de-serialize the complex XML object to C# object

[Serializable] 
public class Country 
{ 
   [XmlElement] 
   public State state{ get; set; } 
} 

[Serializable] 
public class State 
{ 
   [XmlArray("Cities")] 
   [XmlArrayItem("City")] 
   public List Cities { get; set; } 
} 

[Serializable] 
public class City 
{ 
  [XmlAttribute] 
  public string name { get; set;} 

  [XmlAttribute] 
  public string type{ get; set; } 

  [XmlText] 
  public string textString { get; set; } 
}
Now you can call the Deserialize method to convert the xml file to C# object as below
using (var sxmlReader = new StreamReader("worldinfo.xml")) 
{ 
   var serializer = new XmlSerializer(typeof(Countries)); 
   Countries responseData = (Countries)serializer .Deserialize(sxmlReader ); 
}

Frequently Asked Questions On Deserializing XML to C#

1.Can we conver an XML string to C# class?

Yes, Deserializing an XML string into C# class is possible. It will include the libraries that ship with .NET, like System.Xml.Serialization to help you parse your object.

2. How to deserialize  XML string into C# Object?

The code syntax to convert an xml string to a C# class is,

using System.Xml; //include this namespace which contains the XmlSerializer class 

XmlSerializer xmlSerializer = new XmlSerializer(typeof(ClassName));
using (StringReader xmlReader = new StringReader(xmlStringName))
{
    var classObject = (ClassName)xmlSerializer.Deserialize(xmlReader );
}

Or we can use a generic C# Deserialize XML method as below,

public T DeserializeXml<T>(string xmlStringName)
{
    var xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));

    using var stringReader = new StringReader(xmlStringName);
    var xmlReader = new XmlTextReader(stringReader);
    return (T) xmlSerializer.Deserialize(xmlReader);
}

3. How can you deserialize XML file to C# Object?

using System.Xml; 

XmlSerializer xmlSerializer = new XmlSerializer(typeof(ClassName));

using (StreamReader xmlReader = new StreamReader(pathOfYourXMLFile))
{
    var classObject = (ClassName)xmlSerializer.Deserialize(xmlReader );
}

4. How to Deserialize an XML with Attributes in C#

Consider the xml below

<Items category="gadgets">
    <item sku="LP01" price="1000">Laptop1</item>
    <item sku="DT01" price="1000">Desktop1</item>
</Items>

Need to create the following model classes for it.

[XmlRoot(ElementName="item")]
public class Item {
    [XmlAttribute(AttributeName="sku")]
    public string SKU { get; set; }
    [XmlAttribute(AttributeName="price")]
    public string Price { get; set; }
    [XmlText]
    public string Text { get; set; }
}

[XmlRoot(ElementName="items")]
public class Items {
    [XmlElement(ElementName="item")]
    public Item Item { get; set; }
    [XmlAttribute(AttributeName="category")]
    public string Category { get; set; }
}

Now, use the below deserialization logic to deserialize the xml file to object

XmlSerializer xmlSerializer = new XmlSerializer(typeof(Item));

using (StreamReader xmlReader = new StreamReader(pathOfYourXMLFile))
{
    var classObject = (Item)xmlSerializer.Deserialize(xmlReader );
}

Summary

In this article, we explained how to deserialize xml string to object c#, How to deserialize xml to object c# with examples. Hope you find this helpful. Please share your thought and other alternative options, if any, to deserialize xml to dynamic object c# in the comments section below.

Rajeev

View Comments

Recent Posts

OWIN Authentication in .NET Core

OWIN (Open Web Interface for .NET) is an interface between web servers and web applications…

2 years ago

Serializing and Deserializing JSON using Jsonconvertor in C#

JSON (JavaScript Object Notation) is a commonly used data exchange format that facilitates data exchange…

2 years ago

What is CAP Theorem? | What is Brewer’s Theorem?

The CAP theorem is also known as Brewer's theorem. What is CAP Theorem? CAP theorem…

2 years ago

SOLID -Basic Software Design Principles

Some of the Key factors that need to consider while architecting or designing a software…

2 years ago

What is Interface Segregation Principle (ISP) in SOLID Design Principles?

The Interface Segregation Principle (ISP) is one of the SOLID principles of object-oriented design. The…

2 years ago

What is Single Responsibility Principle (SRP) in SOLID Design Priciples?

The Single Responsibility Principle (SRP), also known as the Singularity Principle, is a software design…

2 years ago