BlackWaspTM
XML
.NET 1.1+

XML Serialization (2)

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.

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