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.
- public class Employee
- {
- public int Id = 1;
- public String name = "John Smith";
- public string subject = "Physics";
- }
To serialize this 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();
-
- }
Import the following namespaces to use XmlSerializer and TextWriter in the code,
- using System.Xml.Serialization;
- 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.
- <?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>
Refe to the following snapshot of the XML file generated.