This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET 1.1+

XML Serialization

With XML serialization, the public state of objects can be converted into an XML document. Such XML information is often stored on disk to persist data for later use, or is transported over a network or the Internet to send messages between computers.


The concepts of serialization have already been described in a previous article. For more information, read "Binary Serialization". In this article we will demonstrate the basics of XML serialization. This allows the public state of objects to be converted to XML and later deserialized back into objects.

The main advantage of XML serialization over binary serialization is portability. XML can be interpreted using many development frameworks and languages, and on computers using a variety of operating systems. This allows you to send the XML representation of an object to software applications that are not using the .NET framework or Microsoft Windows. In addition, XML is human-readable and editable, allowing serialized information to be modified using a standard text editor such as Notepad.

There are two key drawbacks of XML serialization. Firstly, only the public state of objects is serialized. Private fields and properties are not represented in the produced XML. Secondly, object references are not maintained when the XML is deserialized into an object; if the original object contained two references to the same object, the deserialization process will generate references to two separate objects.

XML serialization using the .NET framework supports many configuration options that allow the exact structure of the XML to be controlled. However, in this introductory article we will use the default settings for serialization. In future articles we will see how to customise the process further, including changing the names of the XML attributes and elements that are created and using XML schemas.

Serializing To XML

To demonstrate XML serialization we need a sample class. For this, we will use the same Car class that was used in the binary serialization article. The only difference is that the Serializable attribute is not required. The class can be used to represent a car with properties for the model and colour. The class includes a method that allows the number of times that the car has crashed to be incremented, with the count stored in a private field. The ToString method is overridden to allow the state of Car objects to be easily outputted to the Console.

NB: For this example, C#3.0 automatically implemented property syntax has been used. If you are using an earlier language version, expand these to full property declarations with backing store fields.

public class Car
    private int _crashes = 0;

    public string Model { get; set; }

    public string Colour { get; set; }

    public void AddCrash()

    public override string ToString()
        return string.Format("{0} {1}, {2} crash(es).", Colour, Model, _crashes);

Next we need to create a Car object. Add the following code to a console application to create an instance and output its details.

Car car = new Car();
car.Colour = "Red";
car.Model = "Coupe";
Console.WriteLine(car);     // Outputs "Red Coupe, 1 crash(es)."

XML Serialization uses the XmlSerializer class, which is found in the System.Xml.Serialization namespace. In the examples we will be outputting the XML to a file on disk using methods from the System.IO namespace. To simplify the code, add the following two using directives to the code:

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

Performing Serialization

To perform XML serialization we need an instance of the XmlSerializer class. The serializer needs to know the type of object that it will process. This can be provided as a parameter to the constructor. Add the following code to create a serializer for the Car class:

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

Next we need a target for the generated XML. This can be a stream, a TextWriter, an XmlWriter or a subclass of one of these types. In the example code we will serialize to a file using a StreamWriter. Note that the path for the new file is passed into the constructor. You may wish to alter the path or filename. As StreamWriters should be disposed correctly to free up their unmanaged resources, a using statement has been included.

using (StreamWriter writer = new StreamWriter(@"c:\Test\car.xml"))

Finally, to complete the serialization process, the Serialize method is executed, providing the target StreamWriter and the object to be serialized. Ensure that this code is added between the braces of the previous using statement.

serializer.Serialize(writer, car);

You can now execute the code to produce the XML file. After running the program, open the file to see its contents. You should see that the public state from the Model and Colour properties has been included but the private field that holds the number of crashes has not.

Deserializing From XML

The deserialization process uses an XmlSerializer object that is created in exactly the same manner as for serialization. To convert the XML from a stream, TextReader or XmlReader to an object, you call the Deserialize method. This method returns a basic object, which can be cast to the appropriate type.

Execute the following code to deserialize the previously created XML file. Note that although the original object's output indicated that the car had had one crash, the new object has no crashes. As the private field is not included in the XML, the default value for an integer is used.

Car car2;
using (StreamReader reader = new StreamReader(@"c:\Test\car.xml"))
    car2 = (Car)serializer.Deserialize(reader);
Console.WriteLine(car2);    // Outputs "Red Coupe, 0 crash(es)."
9 July 2010