Technology is not science. RSS Feed


XML-serializing a derived collection

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.

 
Posted by Chris Idzerda | 1 Comments | Trackback Url | Bookmark with:        
Tags:

Links to this Post

Comments

Thursday, 15 May 2008 02:46 by Nice Tip
Great tip, especially with the XmlElement feature on collections, I hadn't realised the serialization worked that way.

Name:
URL:
Email:
Comments:

CAPTCHA Image Validation