XML Serialization
Patrick Lavoie
anti-bug informatique
November 22nd 2004
Copyright © 2004
.NET XML serialization is powerful, but there are a few things you need to be aware of when you want to serialize an object. The problem is not really with the serialization itself, but with the deserialization. The deserializer imposes more constraints because it needs to rebuild an object in the exact same state as it was before the serialization.
- Classes *must* have a public default constructor.
- All types *must* be known: all the types that will be serialized. For example, serializing an
Employee instance as object will be a problem during deserialization unless you explicitly identify it as being an Employee instance by using the XmlElement attribute with the typeof parameter. The same applies to ArrayList s (use the XmlArrayItem attribute) and other containers.
When serializing custom collections, you have to either give the serializer the type of objects that collection contains or better yet, your custom collection should implement the Add and the indexer methods with the correct object type.
Examples of serialized objects
Collections
You cannot apply any XML attributes when serializing existing collections, unless you use the attributes override parameter of the serializer, but sometimes you don't even have access to the serializer (suppose that it is wrapped in a black box). In these cases, the object names will be used to name the XML elements.
ArrayList items = new ArrayList();
items.Add("Item 1");
items.Add("Item 2");
<?xml version="1.0"?>
<ArrayOfString xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<string>Item 1</string>
<string>Item 2</string>
</ArrayOfString>
Embedded Collections
When a collection is embedded inside another class, you have all the freedom to customize its XML serialization behavior. It involves additional work but it decouples your object from its XML representation in the way that you could use another kind of collection and still get produce and use the same XML documents.
// The class name will be used as the root XML element.
class MyCollection
{
// Set the name of each XML sub elements.
[XmlElement("MyItem", typeof(string))]
public ArrayList items;
}
MyCollection coll = new MyCollection();
coll.items.Add("Item 1");
coll.items.Add("Item 2");
<?xml version="1.0"?>
<MyCollection>
<MyItem>Item 1</MyItem>
<MyItem>Item 2</MyItem>
</MyCollection>
XmlElementAttribute
There is one thing to know about the XmlElement attribute. When the XmlElement attribute is applied to an array, all of its items are written as a sequence of elements otherwise, the sequence is nested under an element named after the collection member name.
| |