Click here to Skip to main content
15,908,673 members
Articles / Programming Languages / XML
Tip/Trick

XmlObject

Rate me:
Please Sign up or sign in to vote.
4.80/5 (2 votes)
18 Sep 2013CPOL2 min read 10.8K   221   12  
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:

C#
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

C#
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:

C#
/// <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;
            }
        }
    }
C#
/// <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:

C++
/// <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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Daffodil Software Ltd.
India India
Currently using C#, ASP.NET & ASP.NET MVC to Data driven websites , and Software with Agile Development.

My interests involves Programming, development(Software/Web/Mobile App) and Learning/Teaching subjects related to Computer Science/Information Systems. C , C# is the programming languages I have worked in and I love working in C# and other Microsoft Technologies

Comments and Discussions

 
-- There are no messages in this forum --