C# Object XML Serialization

Whether dealing with configuration files or simply the need to transmit structured data objects, nothing can be easier than object serialization to XML in a .NET application where complete serialization of complex objects only requires a few lines of code. The System.Xml.Serialization namespace contains a key element for accomplishing this task, the XMLSerializer class. This class can serialize and deserialize .NET objects based on the public properties with both get and set routines. There is no modification required of the object's class declaration if the property names are acceptable XML tags. Of course, the behavior can be modified through special attribute declarations, but that is beyond the scope of this article.

First, an object may be serialized with the next few lines of code. For this example, PageSettings is the PrintDocument object containing the printer settings. The variable “settings” is of type PageSettings and was passed into the method.

using System.IO;
using System.Xml.Serialization;

Stream data = new MemoryStream();
XmlSerializer serializer = new XmlSerializer(typeof(PageSettings));
serializer.Serialize(data, settings);

Deserializing is no more complicated that serialization into a stream. This time the stream “data” containing the serialized PageSettings object was passed into the method.

using System.IO;
using System.Xml.Serialization;

PageSettings settings;
XmlSerializer serializer = new XmlSerializer(typeof(PageSettings));
settings = serializer.Deserialize(data);

The resulting XML stream can be a file or network stream; it can be easily read or generated by other applications; and it can persist or transmit structured data in just a few lines of code. Once you begin to use serialization in .NET, you will never go back to streaming and parsing in-memory data in any other format.