Serializing objects to XML in C#

Let us first get familiar with the term Serialization. What Serialization is? And how do we use it?

Serialization is the process of converting an object in to stream of bytes. In this article, I will show how to serialize existing objects to XML. XML Serialization converts the public fields and properties of an object into XML stream.

Let us create a console application in the Visual Studio and follow the procedure one by one.

In the application first let us create a class with few properties and initialize them.

  1. public class Employee {  
  2.   
  3.     public int Id = 1;  
  4.     public String name = "John Smith";  
  5.     public string subject = "Physics";  
  6. }  
To serialize this data we will use the XmlSerializer class. Write the following code in the Program.cs
  1. static void Main(string[] args) {  
  2.     Employee bs = new Employee();  
  3.   
  4.     XmlSerializer xs = new XmlSerializer(typeof(Employee));  
  5.   
  6.     TextWriter txtWriter = new StreamWriter(@  
  7.     "D:\Serialization.xml");  
  8.   
  9.     xs.Serialize(txtWriter, bs);  
  10.   
  11.     txtWriter.Close();  
  12.   
  13. }  
The XmlSerializer instance accepts the object type as the parameter. Here the output will be written to a XML file mentioned in the code. TextWriter object requires the path where the serialized object will be saved. Once we call the serialize method we have closed the object of textwriter.

When we run this program we get the XML file at the specified destination in the hard drive.

Let us check the contents of the XML File.
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <Employee  
  3.     xmlns:xsd="http://www.w3.org/2001/XMLSchema"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">  
  5.     <Id>1</Id>  
  6.     <name>John Smith</name>  
  7.     <subject>Physics</subject>  
  8. </Employee>  

 
 
 
 So this is how an object is serialized to XML in C#.