How to tell System.Xml.Serialization.XmlSerializer to only serialize the base class?

I have an array of objects in my base class MyBase. Some of these objects are instances of derived classes, so when I try to serialize this array with System.Xml.Serialization.XmlSerializer, it fails with complaints about derived classes: System.InvalidOperationException: Type DerivedClass was not expected. Use the XmlInclude or SoapInclude attribute to indicate types that are not known statically.

I don't want to serialize derived classes, and I definitely don't want to put [XmlIgnore()]into derived classes (or [XmlInclude()]the base class, for that matter)!

Is there a way to say XmlSerializer only serialize the base for an element like this?

[XmlElement("Items")]
public MyBase[] Items
{
    get
    {
        return items.ToArray();
    }
    set 
    {
        items = new HashSet<MyBase>(value);
    }
}
+3
1

Linq , :

[XmlElement("Items")]
public MyBase[] Items
{
    get
    {
        return items.Where(item => item.GetType() == typeof(MyBase)).ToArray();
    }
    set 
    {
        items = new HashSet<MyBase>(value);
    }
}
+1

All Articles