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";
- }
- 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();
- }
- using System.Xml.Serialization;
- using System.IO;
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>


Luiz CarvalhoPosted May 14, 2020, 1:41 PM
Should the serialize method be inside a try-catch? Or it will always serialize to an XML file, independent of the object?
Nikhil PatelPosted Nov 30, 2018, 12:31 AM
You may want to remove space between @ and " (here @"D:\Serialization.xml")
Suresh MolabantiPosted Jun 29, 2016, 9:50 AM
Its not working to me ..
Omid NasriPosted Jun 29, 2016, 3:09 AM
Nice.
Nikhil SanganiPosted Jun 29, 2016, 2:47 AM
Nice.