Convert your Data Transfer Object to XML (XML Serialization and Deserialization)

Introduction
When we need to transfer our object through internet or need to write in a file then it is necessary to convert it to XML. We can convert object to XML using XML Serialization. In this article we will discuss about how to convert object (It may be entity/ Data Container/ DTO) to XML.

Here we will use XML Serialization & Deserialization for converting our object to XML and XML to Object.

XML Serialization:
XML Serialization is the process of saving class member data into an XML. Only public classes and public properties and fields can be serialised – methods and private members are not serialized and cannot be deserialized. Private classes cannot be serialized and will result in a compilation error.

Let Crate an Entity Class/ Data Transfer Class

public class UserInfoDTO
    {
        public string UserId { get; set; }
        public string UserName { get; set; }
        public string UserAddress { get; set; }
        public string UserPhone { get; set; }
    }

Now we will fill it with data

UserInfoDTO oUserInfoDTO 
                = new UserInfoDTO { UserId = "12", UserName = "Hasibul Haque", 
                                    UserAddress = " Dhaka, Bangladesh", UserPhone = "+8801912104674" };

Now we will convert it to XML using XML Serialization.
Before converting to xml we have to add following namespace.

using System.IO;
using System.Xml;
using System.Xml.Serialization;

Let create a method for Converting Object To XML

public string ToXML(Object oObject)
        {
            XmlDocument xmlDoc = new XmlDocument();
            XmlSerializer xmlSerializer = new XmlSerializer(oObject.GetType());
            using (MemoryStream xmlStream = new MemoryStream())
            {
                xmlSerializer.Serialize(xmlStream, oObject);
                xmlStream.Position = 0;
                xmlDoc.Load(xmlStream);
                return xmlDoc.InnerXml;
            }
        }

This method will return XML string which you can write to file or save to database.

//calling method
string strXML = ToXML(oUserInfoDTO);

We will find following XML after converting our UserInfoDTO object.



12
Hasibul Haque
 Dhaka, Bangladesh
+8801912104674

XML Deserialization:
Deserialization is the reverse process. We will load in an xml, pass the data to the deserializer and it produce an instance of the class populated with the data.

public Object XMLToObject(string XMLString, Object oObject) 
        {
           
            XmlSerializer oXmlSerializer = new XmlSerializer(oObject.GetType());
            oObject = oXmlSerializer.Deserialize(new StringReader(XMLString ));
            return oObject;
          
        }

Download Source Code