Serializing & Deserializing – .NET Managed Object to XML

This article guides you to serialize any managed .NET object to XML and how to deserialize it back to .NET object

What You’ll learn:

  • Serialialization & Deserialization overview
  • Serializing a .NET object to XML with an Example
  • Deserializing XML back to the .NET Object with an Example

Background

In our day to day programming life, we come across many situations where we require to:

  • Send or Receive data between different applications.
  • Write the object data to a file.
  • Transfer the data over the network.
  • and many other..

In all these case, one of the solution we can think of is, converting the data to XML and send it over network or to a file. At the destination, we can deserialize it back to the required .NET object and use it.

Why we need to Serialize / Deserialize an Object?

Because, We cannot send the complex data or objects over the network. Hence, we need to serialize the data in one or the other way.

In the next section, We’ll see what actually Serialization or Deserialization means.

Serialization

Serialization is the process of translating data structures or object data into a format that can be stored (in a file or memory stream or transmitting over a network) and reconstructed back to the object or data structure in the same or different computing environment.

Here, in this article we will see how to Serialize .Net object (instance of user defined Employee class) to XML.

Deserialization

Deserialization is the opposite process of serialization, wherein we will convert the XML data back to the required .NET Object and we can use it as usual in our operations.

Here, in this article we will see how we can we deserialize the XML data back to Employee object.

Namespaces Used

We have 3 namespaces throughout this Demo.

  • System.IO
    • which is used for creating MemoryStream instance.
  • System.Xml
    • which is used for creating XmlDocument instance.
  • System.Xml.Serialization
    • which is used for creating XmlSerializer instance.

We’ll see all these classes in coming sections.

Serializing .Net Object to XML 

As an Example, We will create an web application which looks like this after completion

What it does?

It will accept the required field values from the end user and creates and instance of the user defined class named ‘Employee‘ and then it Serializes it to XML.

Procedure

  • First let’s create a class named ‘Employee‘ as follows:

public class Employee

{                

public int EmployeeGID { getset; }     

public string FirstName { getset; }     

public string LastName { getset; }     

public DateTime DateOfJoining { getset; }     

public Decimal TotalExp { getset; }     

public Decimal Salary { getset; }

}

  • Now, Create an UI which will accept all these data from user.
  • Write a method which takes .NET object as Input and returns the XMLDocument or simply XML as string.
    • Create an instance of XmlDocument class, which will be used to store the serialized XML.
    • Create an instance of XmlSerializer class, which requires the type of object we are going to serialize as input.
    • Create an instance of MemoryStream class, which will be used to temporarily store the serialized XML.
    • use the Serialize() method under XmlSerializer class, one of its constructor requires Stream object to store the serialized XML and an the type of object we are trying to serialize.
      • Serialize(Stream,object)
    • set the position of the stream to 0, as we need to read the data from starting of the stream.
    • Load that stream into XMLDocument object we created in the first step using Load() method under XMLDocument class.
    • Return that XMLDocument object.

 

private XmlDocument ConvertToXML(Object managedClassObject)    

{        

//create an instance of XmlDocument class, it will be used to store the serialized XML        

XmlDocument serializedXMLDoc = new XmlDocument();         //create and instance of XmlSerializer class and tell that instance which Class object you are going to serialize        

XmlSerializer serializer = new XmlSerializer(managedClassObject.GetType());                using(MemoryStream ms = new MemoryStream())        

{            

serializer.Serialize(ms,managedClassObject);            

ms.Position = 0;            

serializedXMLDoc.Load(ms);            

return serializedXMLDoc;        

}    

}

  • In the Click event of submit button (here button named ‘Convert to XML’), write the following code
    • Read data from the form into local variables.
    • Create an instance of Employee class and assign these local variables to the respective properties of the Employee object.
    • Call the ConvertToXML(object), which we created in previous step. We need to pass the Employee object just created as an argument.
    • store the result in a XmlDocument object. and load its inner XML into the read only Textbox to display it on screen.
      • This serialized XML can be stored for later use,
      • can be stored as a file
      • or even can be sent over the network to remote applications.

 

protected void btnSerialize_Click(object sender, EventArgs e)    

{        

int empGid = Convert.ToInt32(txtEmployeeGID.Text.Trim());        

string fname = txtFirstName.Text.Trim();        

string lname = txtLastName.Text.Trim();        

DateTime doj = DateTime.Parse(txtDOJ.Text);        

decimal totalExp = Decimal.Parse(txtTotalExp.Text.Trim());        

decimal sal = Decimal.Parse(txtSalary.Text.Trim());        

Employee employee = new Employee()         

            

EmployeeGID = empGid,            

FirstName = fname,            

LastName = lname,            

DateOfJoining = doj,            

TotalExp = totalExp,            

Salary = sal        

};        

XmlDocument serializedXML = ConvertToXML(employee);        

txtSerializedXML.Text = serializedXML.InnerXml;          

}

 

Deserializing XML back to .NET Object

As an Example, We will create an web application which looks like this after completion

What it does?

It will accept the previously serialized XML as an input from the end user and Deserializes it back to ‘Employee‘ object.

Procedure

  • As, we already created Employee class, just go ahead and create an UI which will accept XML as Input and display all the Employee properties in the text boxes after deserialization.
  • Create a method named ‘ConvertToObject‘ which will accept the XML which needs to be deserialized as string and the object to which we should deserialize the XML as arguments.
    • Create and instance of XmlSerializer class using one of its constructor which accepts the type of object to which we are going to deserialize the XML.
    • Call the Deserialize(string xml) method of XmlSerializer class which deserializes the Xml string passed to it and returns an object.

– As a generic method, we are passing an object of Type Object and returning the same.

private Object ConvertToObject(string xmlData, Object managedClassObject)    {                //create and instance of XmlSerializer class and tell that instance which Class object you are going to deserialize        XmlSerializer deserializer = new XmlSerializer(managedClassObject.GetType());         managedClassObject = deserializer.Deserialize(new StringReader(xmlData));         return managedClassObject;    }

  • Under the click event of the submit button (here named as ‘Convert to Object’), write the following code:
    • Create an instance of Employee class.
    • Call the ConvertToObject() method we just created and pass the xml to be deserialized as first argument and the Employee instance as second argument.
    • fill in all the properties of Employee object into the textboxes
      • We can use this object however we want. just for demo purpose, we are displaying them on screen in textboxes.

 

protected void btnDeSerialize_Click(object sender, EventArgs e)    

{        

Employee empObj = new Employee();        

empObj = (Employee)ConvertToObject(txtSerializedXML.Text, empObj);        

txtEmployeeGID.Text = empObj.EmployeeGID.ToString();        

txtFirstName.Text = empObj.FirstName;        

txtLastName.Text = empObj.LastName;        

txtDOJ.Text = empObj.DateOfJoining.Date.ToShortDateString();        

txtTotalExp.Text = empObj.TotalExp.ToString();        

txtSalary.Text = empObj.Salary.ToString(“0.00”);          

}

You can download the complete working solution in the download links available in the downloads section of this article.

Hope, you have successfully Serialized and Deserialized the .NET object into XML.

Happy Coding!!!

 

I am a Consultant at Microsoft currently living in Hyderabad, India. My interests range from blogging to technology especially into /Web. I am also interested in movies and photography.

Leave a Reply

Skip to toolbar