Serializing a single object in XML format is as simple as the other types of serialization. However, you can’t serialize multiple objects into the same file because of the specifications of an XML document. An XML document has a single root element, so all the objects must have a common root. In other words, you can’t serialize two Rectangle objects one after the other, as you did in the previous section with the SOAP and binary formatters. However, you can create an array with as many objects as you like and serialize it in XML format. The array is a single object, which can be serialized. Because XML is a universal standard, you can’t use it to serialize data structures that are specific to the Framework. You can’t serialize ArrayLists, HashTables, and other collections to XML format.
How about the objects you can serialize? The XmlSerializer class serializes the public properties of objects and doesn’t care about the source of the data. When you serialize a Rectangle object, the following data is created:
<?xml version="1.0" encoding="utf-8"?> <Rectangle xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Location> <X>10</X> <Y>10</Y> </Location> <Size> <Width>100</Width> <Height>160</Height> </Size> <X>10</X> <Y>10</Y> <Width>100</Width> <Height>160</Height> </Rectangle>
This is a well-formed XML document. XML is discussed in more detail later in this chapter, but for the purposes of XML serialization, you don’t have to know anything about XML. Just keep in mind that every item in this document is delimited by a pair of tags in angle brackets. The tags are named after the properties of the object, and you need not be a rocket scientist to understand that this document represents a Rectangle object. As you can see, the XmlSerializer extracted the basic properties of the Rectangle object. There’s some redundancy in this file because the values of the properties appear twice. This isn’t part of the XML specification; the document contains the values of the following properties: Location, Size, X, Y, Width, and Height. The Rectangle object exposes additional properties, such as the Top, Bottom, and so on, but these values aren’t serialized. The Location property is an object, which in turn exposes the X and Y properties. The values of these properties appear within the Location segment of the document, as well as separate values near the end of the file. The same happens with the Size property.
To deserialize the data and create a new Rectangle object with the same properties as the original one, set up a Stream object and an XmlSerializer object, and then call the XmlSerializer object’s Deserialize method:
Imports System.Xml.Serialization Dim serializer As New XmlSerializer(Rectangle.GetType) Dim FS As FileStream FS = New FileStream(path, FileMode.Open) Dim R As Rectangle R = serializer.Deserialize(FS) FS.Close()