How to Serialize a Collection
October 19, 2006
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;
>
> }
>
> }
>
> }