How to Serialize a Collection

In a fragment of a code I’m working on, I must serialize a collection of links into an XML file. Fortunately, .NET Framework provides a quick XmlSerializer class to do the dirty job for you.

Well, almost…

The problem

If you try to serialize a class derived from CollectionBase, the Serialize method will throw a nasty exception.

The workaround

Use a container class, put the CollectionBase-derived class as a property, decorate this property with XmlArray and XmlArrayItem tags.

[Serializable]

public class CollectionContainer

{

private LinkCollection _links= new ColeccionEnlaces();

[XmlArray(“Links”)]

[XmlArrayItem(“Link”,typeof(Link))]

public LinkCollection Links

{

get

{

return _links;

}

set

{

_links = value;

}

}

}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.