XML Serialization of a Collection with properties
In this particular project we needed to serialize a collection of items and include an attribute in each one. Saddly, XmlSerializer seems to not support that directly but there is a workaround: use containment instead of derivation and then apply the [XmlElement] attribute to the collection property to get rid of the unwanted wrapping xml tag. For example:
A class derived from a collection class will XML-serialize only the collection, not any additional properties in your derived class.
public class NamedNodeList : List<Node>
{
public string Name { get; set; } // ignored during XML serialization
}
The work-around is to use containment instead of derivation.
public class NamedNodeList
{
public string Name { get; set; }
public List<Node> Nodes { get; set; }
}
This works except you will get an additional wrapping element around the collection. To get rid of this wrapper, use the XmlElement attribute on the collection property.
[XmlElement]
public List<Node> Nodes { get; set; }
In fact, applying the XmlElement attribute to any collection member in any context (not just the derivation context here) will give you a collection not surrounded by a containing element.
From the Chris Idzerda blog at http://blogs.vertigo.com/personal/chris/Blog/archive/2008/05/14/xml-serializing-a-derived-collection.aspx