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

Data Object to XML (Vice-versa) using C#

0.00/5 (No votes)
25 Oct 2013 3  
XML Serialization & Deserialization for converting our object to XML and XML to Object

Introduction

Serialization is the process of converting specific data to a format that can be stored or transmitted, and later re-used to retrieve the information in its initial state. In this tip, I will show some of the ways to serialize existing objects to XML and then deserialize them.

Why need to convert object to XML & XML to object:

  • Transfer our object over the internet
  • Write to a file then it is necessary to convert it to XML
  • Complex service

Serialization/de-serialization is a very important feature of an application, especially when it needs to communicate with another application by sending and receiving data.

You can download the source code from this link.

Background

Here we will use XML Serialization & Deserialization for converting our object to XML and XML to Object. Now we will learn the concept of serialization & deserialization.

Serialization

XML Serialization is the process of saving class member data into an XML. The Microsoft .NET Framework includes powerful objects that can serialize any object to XML. The System.Xml.Serialization namespace provides this capability.

Deserialization

The deserialization process goes the other way around - it converts the bytes of data obtained from a specific source to a workable object or data unit. We will load in an XML, then pass the data to the deserializer and it will produce an instance of the class populated with the data.

Using the Code

Here, I will be reading and writing an employee class. If you need a similar employee class and read/write that from your application, then you can re-use the complete class that I am going to put it at the end of the post.

Follow these steps to create a Windows application that creates an object, and then serializes its state to XML:

  1. In Visual C#, create a new Windows Application project.
  2. On the Project menu, click Add Class to add a new class to the project.
  3. In the Add New Item dialog box, change the name of the class to Employee.
  4. Click Add. A new class is created.
    Note In Visual Studio .NET 2010, click Open.
  5. Add the following code after the Public Class Employee statement:
public class Employee
{
     public int employee_code {set; get; } 
     public string first_name {set; get; } 
     public string middle_name {set; get; }
     public string last_name {set; get; }
     public string designation {set; get; }
     public string department {set; get; }
     public string present_address {set; get; }
     public string permament_address {set; get; }
     public DateTime DOB {set; get; }
     public Double Gross_Salary {set; get; }
} 

Switch to the code window for frmObject2XML.cs in Visual Studio, declare and create an instance of the Employee class:

Now we will convert it to XML using XM Serialization. Before converting to XML, we have to add the following namespace:

using System.IO;  

It is used for MemoryStream class using System.Xml;

using System.Xml.Serialization;

It is used for XML Serialization.

Let's create a method for converting the object to XML.

public string CreateXML(Object YourClassObject){    
      XmlDocument xmlDoc =new XmlDocument();   //Represents an XML document, 
      			// Initializes a new instance of the XmlDocument class.          
      XmlSerializer xmlSerializer = new XmlSerializer(YourClassObject.GetType());            
    // Creates a stream whose backing store is memory. 
       using (MemoryStream xmlStream =new MemoryStream())
       { 
        xmlSerializer.Serialize(xmlStream, YourClassObject);
        xmlStream.Position = 0;
        //Loads the XML document from the specified string.
        xmlDoc.Load(xmlStream); 
        return xmlDoc.InnerXml;
       }
}

This method will return a string containing XML.

Using CreateXML method.

string strView =CreateXML(YourClassObject);

We will then find the following XML after converting ourYourClassObject object.

<?xml version="1.0"?>
<Employee xmlns:xsi="<a target="_blank" href="http://www.w3.org/2001/XMLSchema-instance">
<employee_code>10</employee_code>
<first_name>Monotosh</first_name>
<middle_name></middle_name>
<last_name>Roy</last_name>
<designation>SoftwareEngineer</designation>
<department>Software</department>
<present_address>Dhaka</present_address>
<permament_address>Magura</permament_address>
<DOB>2013-10-23T00:00:00</DOB>
<Gross_<wbr />Salary>

Let's create a method for converting the XML to object.

public Object CreateObject(string XMLString,Object YourClassObject){            
    XmlSerializer oXmlSerializer =new XmlSerializer(YourClassObject.GetType()); 
    //The StringReader will be the stream holder for the existing XML file 
    YourClassObject = oXmlSerializer.Deserialize(new StringReader(XMLString)); 
 //initially deserialized, the data is represented by an object without a defined type 
 return YourClassObject;
 }
} 

Using CreateObject method:

Employee objemp = newEmployee();  
objemp = (Employee)CreateObject(txtXML.Text, objemp)

MessageBox.Show(Employee Code: "+ objemp.employee_code + "\n"+ 
"Employee Name: "+ objemp.first_name +" "+ objemp.middle_name + 
" " + objemp.last_name + "\n" +"Gross Salary: " + objemp.Gross_Salary);  

Hope this post will help you to learn data object convert to XML & XML to object. Post your queries if you have any or if there is anything else, please share. Keep visiting for new posts here. Have a good day!

Points of Interest

  • Easy understanding object & XML conversion process

History

  • 25th October, 2013: Initial post

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