Thursday, November 2, 2017

XML to Object and vice versa in c# using DataContractSerializer


From conversion of XML to object and vice versa, we already have helper classes in .net. However, on this page, I have tried to implement a generic helper class for these operations. There are two functions in the helper which converts an xml string to class object and another function for converting class object to XML string.
To use DataContractSerializer class, you need to add reference System.Runtime.Serialization in your project.

Helper class:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace ConsoleApp2
{
    /// <summary>
    /// Helper class for xml parsing
    /// </summary>
    /// <typeparam name="T">class object to/to be parsed</typeparam>
    public class DataContractSerializationHelper<T>
    {
        /// <summary>
        /// Converts xml string to Object
        /// </summary>
        /// <param name="xmlText"></param>
        /// <returns></returns>
        public  T Xml_To_Object(string xmlText)
        {

            T returnObject;
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xmlText);

            using (StringReader stringReader = new StringReader(doc.OuterXml))
            {
                using (XmlTextReader xmlReader = new XmlTextReader(stringReader))
                {
                    DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                    returnObject = (T)serializer.ReadObject(xmlReader);
                }

            }

            return returnObject;
        }

        /// <summary>
        /// Converts object to xmldocument
        /// </summary>
        /// <param name="myObject"></param>
        /// <returns></returns>
        public XmlDocument Object_To_XML(T myObject)
        {

            XmlDocument xmlDocument = null;

            using (StringWriter stringWriter = new StringWriter())
            {
                using (XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter))
                {
                    DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                    serializer.WriteObject(xmlTextWriter, myObject);
                    xmlDocument = new XmlDocument();
                    xmlDocument.InnerXml = stringWriter.GetStringBuilder().ToString();
                }
            }

            return xmlDocument;
        }
    }   
}

Sample class ( to be passed as generic):

    public class testclass
    {
        public int id { getset; }
        public string name { getset; }
    }


Implementation of above helper class ( assuming the implementation done in console app) :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {

            DataContractSerializationHelper<testclass> helper = new                           DataContractSerializationHelper<testclass>();


            // conversion from object to xmldocument
            testclass obj = new testclass ();
            obj.id = 1;
            obj.name = "hello world";
            var xmldoc = helper.Object_To_XML(obj);


            // conversion from xmlstring to object
//note : in case you get namespace error replace 'ConsoleApp2' of testxml with the namespace of the class
            string testxml = "<testclass xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.datacontract.org/2004/07/ConsoleApp2\"><id>1</id><name>hello world</name></testclass>";
            var testclassObject = helper.Xml_To_Object(testxml);


        }
    }
}



Note: If you need to have a function which will directly use the XML file URL or you need to export the class object to an XML file and save it in a location, you can give it a try it. Or leave a comment and I will update the post with other functions as well.







No comments:

Post a Comment