Serializing Object to XML in C#

What is Serialization?

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

Open Visual Studio. Go to File->New->Project,

Choose Console Application. In the application first let us write a class with a few properties.

  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 we will use the XmlSerializer class. Write the following code in the Program.cs,
  1. static void Main(string[] args)   
  2. {  
  3.     Employee bs = new Employee();  
  5.     XmlSerializer xs = new XmlSerializer(typeof(Employee));  
  7.     TextWriter txtWriter = new StreamWriter(@ "D:\Serialization.xml");  
  9.     xs.Serialize(txtWriter, bs);  
  11.     txtWriter.Close();  
  13. }  
Import the following namespaces to use XmlSerializer and TextWriter in the code,
  1. using System.Xml.Serialization;  
  2. using System.IO;  
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. Here I have defined the path in the D drive. 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"?> -  
  3. <Employee xmlns:xsd="" xmlns:xsi="">  
  5.     <Id>1</Id>  
  7.     <name>John Smith</name>  
  9.     <subject>Physics</subject>  
  11. </Employee>  
Refe to the following snapshot of the XML file generated.