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.
- public class Employee {
- public int Id = 1;
- public String name = "John Smith";
- public string subject = "Physics";
- }
To serialize this data we will use the XmlSerializer class. Write the following code in the Program.cs
- static void Main(string[] args) {
- Employee bs = new Employee();
- XmlSerializer xs = new XmlSerializer(typeof(Employee));
- TextWriter txtWriter = new StreamWriter(@
- "D:\Serialization.xml");
- xs.Serialize(txtWriter, bs);
- txtWriter.Close();
- }
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.
- <?xml version="1.0" encoding="UTF-8"?>
- <Employee
- xmlns:xsd="http://www.w3.org/2001/XMLSchema"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
- <Id>1</Id>
- <name>John Smith</name>
- <subject>Physics</subject>
- </Employee>

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

Santhakumar MunuswamyPosted Apr 20, 2015, 2:16 PM
Thanks for sharing
Manoj KulkarniPosted Apr 20, 2015, 6:42 AM
Thank you for sharing the information