Click here to Skip to main content
12,069,649 members (56,282 online)
Click here to Skip to main content
Add your own
alternative version

Stats

76.4K views
3.2K downloads
17 bookmarked
Posted

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

, 25 Oct 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

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

You may also be interested in...

Comments and Discussions

 
QuestionThank You. Please help... !!!! Pin
Member 109889904-Aug-14 12:25
memberMember 109889904-Aug-14 12:25 
QuestionA bit difference in result Pin
shish201018-Jun-14 0:10
membershish201018-Jun-14 0:10 
QuestionSOAP Pin
Alex JMW28-Oct-13 20:04
memberAlex JMW28-Oct-13 20:04 
QuestionJust a minor improvement suggestion Pin
Masked Dev25-Oct-13 6:23
memberMasked Dev25-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.

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