Click here to Skip to main content
13,861,262 members
Click here to Skip to main content
Add your own
alternative version


20 bookmarked
Posted 25 Oct 2013
Licenced CPOL

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

, 25 Oct 2013
Rate this:
Please Sign up or sign in to vote.
XML Serialization & Deserialization for converting our object to XML and XML to Object


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.


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.


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.


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.
        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="">
<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


  • 25th October, 2013: Initial post


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Monotosh Roy Mon
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-

You may also be interested in...


Comments and Discussions

QuestionThank You. Please help... !!!! Pin
neuronring4-Aug-14 12:25
memberneuronring4-Aug-14 12:25 
QuestionA bit difference in result Pin
shish201018-Jun-14 0:10
membershish201018-Jun-14 0:10 
QuestionSOAP Pin
Alex (RSA)28-Oct-13 20:04
professionalAlex (RSA)28-Oct-13 20:04 
QuestionJust a minor improvement suggestion Pin
MaskedDev25-Oct-13 6:23
professionalMaskedDev25-Oct-13 6: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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web02 | 2.8.190214.1 | Last Updated 25 Oct 2013
Article Copyright 2013 by Monotosh Roy Mon
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid