Den is a DZone Zone Leader and has posted 460 posts at DZone. You can read more from them at their website. View Full User Profile

Serializing and deserializing objects to XML in C#

06.15.2010
| 65433 views |
  • submit to reddit

Serialization is the process in converting specific information (data) to a format that can be stored or transmitted, and later re-used to retrieve the information in its initial state. In this article, I will show some of the ways to serialize existing objects to XML and then deserialize them.

First of all, I am going to have a custom class that represents a unit that contains data about a city:

public class City
{
public string Name { get; set; }
public string State { get; set; }
public string County { get; set; }
public bool IsCountyCenter { get; set; }
public bool IsStateCapital { get; set; }
public int Population { get; set; }
}

Before going any further, I need to instantiate the class and assign some values to the existing properties. Inside the main application class, I used the following code to customize my instance:

City city = new City();
city.Name = "Independence";
city.State = "KS";
city.County = "Montgomery";
city.IsCountyCenter = true;
city.IsStateCapital = false;
city.Population = 10000;

To serialize this specific object, I can use the XmlSerializer class. I’ve seen people who work with .NET write XML data via XmlWriter and retrieve each property, writing it to separate nodes. This is also a choice, however not the most reliable and since there is a built-in serialization class, unless it extremely doesn’t fit your needs, I’d recommend sticking with it.

The serialization code looks like this:

XmlSerializer serializer = new XmlSerializer(city.GetType());
StreamWriter writer = new StreamWriter(@"D:\Temporary\myfile.xml");
serializer.Serialize(writer.BaseStream, city);

The XmlSerializer instance accepts the object type as the parameter, so I am getting the type of the City instance. In my case, I am writing the serialization output to a file, however it can be written to any passed stream. The second parameter for the Serialize method is the instance that needs to be serialized.

The stored data will look like this:

<?xml version="1.0"?>
<City xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Name>Independence</Name>
<State>KS</State>
<County>Montgomery</County>
<IsCountyCenter>true</IsCountyCenter>
<IsStateCapital>false</IsStateCapital>
<Population>10000</Population>
</City>

The deserialization process goes the other way around – it converts the bytes of data obtained from a specific source to a workable object or data unit. In .NET, the same XmlSerializer class is used to deserialize data.

For the case presented above, the deserialization code looks like this:

City city = new City();

XmlSerializer serializer = new XmlSerializer(city.GetType());

StreamReader reader = new StreamReader(@"D:\Temporary\myfile.xml");
object deserialized = serializer.Deserialize(reader.BaseStream);

city = (City)deserialized;

First of all, I have an instance of the City class. It will become the deserialized object once the process is complete. Same as for the serialization process, I am getting the type for the target class instance and pass it to the existing XmlSerializer instance. The StreamReader will be the stream holder for the existing XML file. When initially deserialized, the data is represented by an object without a defined type. Later on, the developer can convert the object to fit the needed type and access the data.

Serialization not only saves a lot of time when existing data needs to be transferred or stored for later re-use, but it also makes the process more reliable by avoiding hand-written XML formatting and data placement mistakes.