Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

XmlObject

0.00/5 (No votes)
18 Sep 2013 1  
Creating XML from Object & populating your Object from XML using one line of code

Introduction

Creating XML from Complex Object type is a tedious task, and populating Object from XML by parsing it is even worse.

I have developed a static library for .NET Framework named XmlObject. Using XmlObject in your project, you can populate data from XML to Object without parsing, and also can create XML from Object of any Type, just by using one line of code.

Instead, if we have XSD, then XSDtoCode can do all these tasks.

Simple Steps to Create XML From Object

Basic Step

Create an instance of SerializerDeserializer in namespace XmlObject as:

yourClassName obj = new  yourClassName( );
SerializerDeserializer<yourClassName> 
xmlPlayer = new  SerializerDeserializer<yourClassName>();
string xml = xmlPlayer.Serialize(obj);

That's it. Your XML is created now.

Simple Steps to Populate Object From XML

Basic Steps

SerializerDeserializer<yourClassName> 
xmlPlayer = new  SerializerDeserializer<yourClassName>();
yourClassName obj = xmlPlayer.Serialize(xmlString);

That's it. The basic requirement is fulfilled now.

But now, there may be some problem you will face, as all int are initialized as zero (its default value) so node will be created with its 0 value in your XML, this may cause difficulty in different cases. Now, here is a standard to be followed.

Standard Way to Create your Class/Model

You can see in the sample project as well.
For example, let's take a Student class and Address class as below:

/// <summary>
    /// Student Class
    /// </summary>
    public class Student
    {
        private string nameField;
        private Nullable<int> ageField;
        private Address addressField;

        public string Name
        {
            get
            {
                return this.nameField;
            }
            set
            {
                this.nameField = value;
            }
        }
        
        public int Age
        {
            get
            {
                if (this.ageField.HasValue)
                    return this.ageField.Value;
                else
                    return default(int);
            }

            set
            {
                this.ageField = value;
            }
        }
        /// <summary>
        ///To remove age tag if age is note specified
        /// </summary>
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public bool AgeSpcified
        {
            get
            {
                return this.ageField.HasValue;

            }
            set
            {
                if (value == false)
                    this.ageField = null;
            }
        }

        public Address Address
        {
            get
            {
                return this.addressField;
            }
            set
            {
                this.addressField = value;
            }
        }
    }
 /// <summary>
    /// Address Class
    /// </summary>
    public partial class Address
    {
        private string cityField;
        private string countryField;

        public string City
        {
            get
            {
                return this.cityField;
            }

            set
            {
                this.cityField = value;
            }
        }

        public string Country
        {
            get
            {
                return this.countryField;
            }
            set
            {
                this.countryField = value;
            }
        }

        private System.Nullable<int> streetField;

        public int street
        {
            get
            {
                if (this.streetField.HasValue)
                {
                    return this.streetField.Value;
                }
                else
                {
                    return default(int);
                }
            }
            set
            {
                this.streetField = value;
            }
        }  

This is the proper way to Get and Set your class properties.
Note: With all Int, there is a field called Specified, so if you populate value of it in your object, a corresponding node will be created, otherwise not.

Specific Requirements

Sometimes, people say we need to create all corresponding nodes in XML and it doesn't matter whether they are initialized by the user or not. In such case, we just need to create a constructor, as shown below:

 /// <summary>
    /// Student Class
    /// </summary>
    public class Student
    {
        public Student()
        {
            this.Address = new Address();
        }
        private string nameField;
        private Nullable<int> ageField;
        private Address addressField;


        public string Name
        {
            get
            {
                return this.nameField;
            }
            set
            {
                this.nameField = value;
            }
        }
        
        public int Age
        {
            get
            {
                if (this.ageField.HasValue)
                    return this.ageField.Value;
                else
                    return default(int);
            }

            set
            {
                this.ageField = value;
            }
        }
        /// <summary>
        ///To remove age tag if age is note specified
        /// </summary>
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public bool AgeSpcified
        {
            get
            {
                return this.ageField.HasValue;

            }
            set
            {
                if (value == false)
                    this.ageField = null;
            }
        }

        public Address Address
        {
            get
            {
                return this.addressField;
            }
            set
            {
                this.addressField = value;
            }
        }
    }

You need to initialize all properties in the constructor.

Points of Interest

XmlObject is very helpful in project where we need to parse big XML responses, and also need to create big XML Request as well. It reduces the development time and increases the readability of code and also makes parsing faster as there are no "if else" at each step of node parsing. It also replaces more than 100 lines of code to one. ;)

Currently, I have tested it with some of my Objects. And for SOAP XML Request/Response, you just need to remove SOAP Node (Header) and just use the main XML for parsing and creating DTO.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here