Have you ever tried to xml serialize a class hierarchy derived from CollectionBase?

If you ever tried to serialize and deserialize a hierachy of classes starting a CollectionBase, you found that it doesn't work.

Consider a hierarchy like:

[XmlInclude(“DerivedCollection“)]
public class MyBase : CollectionBase
{
 // implement Add and Item and everything else you need
}

public class DerivedCollection : MyBase
{
 // implement Add and Item and everything else you need
}

If you serialize it with an XmlSerializer instantiated for the base class:

XmlSerializer serializer = new XmlSerializer( typeof( MyBase ) );

You will not be able to deserialize the XML properly. However, it gets worse if you try to serialize and deserialize another class that defines a field of MyBase. Read all the details of the problem here.

Published Monday, September 15, 2003 8:04 PM by ChristophDotNet
Filed under:

Comments

# re: Have you ever tried to xml serialize a class hierarchy derived from CollectionBase?

Tuesday, September 16, 2003 11:05 AM by Matt Berther
If Im understanding what you're after, I've have managed to pull this off by implementing IXmlSerialzable in my CollectionBase derived class.

# re: Have you ever tried to xml serialize a class hierarchy derived from CollectionBase?

Monday, December 29, 2003 4:16 AM by Phenaste
Okay !

I was in the same problem. A piece of code bring me on the right way.
When you inherits from CollectionBase and you want to serialize, don't to forget to implement an Add methods with the type of elements as argument, ie :

public int Add(ElementType element)
{
return List.Add(element);
}

If you forget it, your xml output will be untyped or not under write-control.

To avoid an exception, add [XmlInclude(typeof(ElementType)] just before the collection class.

# re: Have you ever tried to xml serialize a class hierarchy derived from CollectionBase?

Tuesday, January 06, 2004 10:44 PM by ChristophDotNet
Phenaste,

Are you sure you are getting this to work serializing and deserializing the XML? Are you actually deriving a class from CollectionBase and then another class from that?

I'd be very interested to see your code.

Christoph

# re: Have you ever tried to xml serialize a class hierarchy derived from CollectionBase?

Friday, March 06, 2009 11:00 AM by ...

Interessante Informationen.

Leave a Comment

(required) 
(required) 
(optional)
(required)