Deserialize XML into C# Object/Type dynamically

Deserialize XML into C ObjectType dynamically

Today in this article, we will see Deserialize XML into C# Object.

If you are looking for better a way to call a generic method when the type of parameter isn’t known at compile-time but want to obtain it dynamically at runtime then below logic could be very useful.

In our last article, we already looked similar generic approach for JSON to Type conversion dynamically.

Today in this article, we will cover below aspects,

On similar lines, we will convert XML object into a type of your choice dynamically. Here I am using generics <T> to denote the same.

Scenario-I

I have simple XML (“user.xml“) as shown below,

<?xml version="1.0" encoding="utf-8" ?>
<UserDetails>
  <ID>1020</ID>
  <Name>ABCD</Name>
  <City>NY</City>
  <Country>USA</Country>
</UserDetails>

Scenario-II

Let’s consider a complex XML ( “usercomplex.xml“) with array example,

<?xml version="1.0" encoding="utf-8" ?>
<User>
  <Details>
    <ID>1020</ID>
    <Name>ABCD</Name>
    <City>NY</City>
    <Country>USA</Country>
  </Details>
  <Details>
    <ID>1020</ID>
    <Name>ABCD</Name>
    <City>NY</City>
    <Country>USA</Country>
  </Details>
</User>

Below logic will generate type dynamically which can be cast to appropriate type as needed.

Let’s use the below method to convert this XML into type,

 
private static T GetXMLGenericType<T>(string xmlFile)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            var generatedType = (T)serializer.Deserialize(new 
                                   StreamReader(xmlFile));
            return (T)Convert.ChangeType(generatedType, typeof(T));
        }


Deserialize XML into C ObjectType dynamically

Client-side code

Let’s assume you would like to map the XML data to a specific type on called side.

The below client class can also be easily created using VS2017 IDE Paste special utility .

Deserialize XML into C ObjectType dynamically

    
    [Serializable()]
    public class UserDetails
    {
        public string ID { get; set; }
        public string Name { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
    }


Scenario I

Client-side code for the Scenario I will be as below,

UserDetails userData = GetXMLGenericType("Users.xml");

OutPut:

The output now can be mapped to Object/Type as below,

Deserialize XML into C ObjectType dynamically

Scenario II

Client-side code for will be as below,

User userxmlData = GetXMLGenericType<User>("UsersComplex.xml");

The mapping class will be generated as below,

    

    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
    public partial class User
    {
        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute("Details")]
        public UserDetails[] Details { get; set; }
        
    }


The output now we get as array of object as below,

Deserialize XML into C ObjectType dynamically

Do you have any better suggestions for the above? Please sound off in the comments below!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



2 thoughts on “Deserialize XML into C# Object/Type dynamically

Leave a Reply

Your email address will not be published. Required fields are marked *