Object To XML and Vice Versa using C#

Sometimes in web applications we like to save or send our data as XML to the SQL databases.
It’s mostly done when there is a large chunk of data or we like to convert our entity model objects to XML.
It makes it easier to move data from web applications to SQL database and vice versa.
Here I’ll share a code snippet to convert C# object to XML and XML to object C#.

C# Object to XML:

To convert an object to XML, we’ll make use of XmlSerializer to serialize and XmlTextWriter to output the XML string.
Here is how the code looks like :

public static string GetXMLFromObject(object o)
{
    StringWriter sw = new StringWriter();
    XmlTextWriter tw = null;
    try
    {
        XmlSerializer serializer = new XmlSerializer(o.GetType());
        tw = new XmlTextWriter(sw);
        serializer.Serialize(tw, o);
    }
    catch (Exception ex)
    {
        //Handle Exception Code
    }
    finally
    {
        sw.Close();
        if (tw != null)
        {
            tw.Close();
        }
    }
    return sw.ToString();
}

XML to Object C# :

Similarly, to convert an XML string to object we make use of the XmlSerializer to deserialize and XmlTextReader to read the XML string.
Here is how the code to convert XML to objects looks like :

public static Object ObjectToXML(string xml, Type objectType)
{
    StringReader strReader = null;
    XmlSerializer serializer = null;
    XmlTextReader xmlReader = null;
    Object obj = null;
    try
    {
        strReader = new StringReader(xml);
        serializer = new XmlSerializer(objectType);
        xmlReader = new XmlTextReader(strReader);
        obj = serializer.Deserialize(xmlReader);
    }
    catch (Exception exp)
    {
        //Handle Exception Code
    }
    finally
    {
        if (xmlReader != null)
        {
            xmlReader.Close();
        }
        if (strReader != null)
        {
            strReader.Close();
        }
    }
    return obj;
}

Calling :

Employee emp = new Employee();
emp.FirstName = "Ujjwala Datta";
emp.LastName = "Kalluri";

string xml = GetXMLFromObject(emp);
<?xml version="1.0" encoding="utf-16" ?> 
- <Employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <FirstName>Ujjwala Datta</FirstName> 
  <LastName>Kalluri</LastName> 
  </Employee>

Object obj = ObjectToXML(xml,typeof(Employee));
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s