Click here to Skip to main content
15,881,635 members
Articles / Programming Languages / C# 4.0
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
4.77/5 (10 votes)
25 Oct 2013CPOL3 min read 164.2K   4.6K   20   4
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.

Image 1

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

C#
using System.IO;  

It is used for MemoryStream class using System.Xml;

C#
using System.Xml.Serialization;

It is used for XML Serialization.

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

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

C#
string strView =CreateXML(YourClassObject);

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

XML
<?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.

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

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

Image 2

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

Image 3

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


Written By
Architect
Bangladesh Bangladesh
My Name is Monotosh Roy (Mon), Completed Bachelor In Computer Science from West Bengal University of Technology, India & M.Sc. In Computer Science & Engineering from United International University. I have lots of experience on core software development with API service integration more than 8 years using tools- ASP.Net, C#, PL/SQL, WCF, SAP, SugerCRM, Salesforce, VBA Excel Export, Web Service, PHP, and MVC 2/3/4 etc. I had successfully implemented more than 200 projects in boundary as well across boundary followed by project management tools like as Agile, PMP & BCM-

Worked on freelancing marketplace in US & other countries through Odesk, Elance & Freelancer etc

LinkedIn Profile- bd.linkedin.com/in/monotoshroy/

Comments and Discussions

 
QuestionThank You. Please help... !!!! Pin
neuronring4-Aug-14 11:25
neuronring4-Aug-14 11:25 
QuestionA bit difference in result Pin
shish201017-Jun-14 23:10
shish201017-Jun-14 23:10 
QuestionSOAP Pin
Alex (RSA)28-Oct-13 19:04
professionalAlex (RSA)28-Oct-13 19:04 
You forgot to mention that this technique only works for 'Simple Objects'. It is good for objects that only store data (properties), but once you add methods to your class, that can't be serialised to xml and the code won't run anymore.
AlexC

QuestionJust a minor improvement suggestion Pin
MaskedDev25-Oct-13 5:23
professionalMaskedDev25-Oct-13 5:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.