I receive XML fragments similar to this:
<ListOfThings>
<BaseClass>
<BaseProperty>Base property</BaseProperty>
</BaseClass>
<Derived1>
<BaseProperty>Different base property</BaseProperty>
<DerivedProperty1>Something</DerivedProperty1>
</Derived1>
<Derived2>
<BaseProperty>Different base property</BaseProperty>
<DerivedProperty2>Something else</DerivedProperty2>
</Derived2>
</ListOfThings>
I have a corresponding set of classes:
public class BaseClass {...}
public class Derived1 : BaseClass {...}
public class Derived2 : BaseClass {...}
and I want to deserialize the XML fragment into a List<BaseClass>
.
Effectively I want to solve two problems at once:
- Deserializing a list of derived classes
- Deserializing into a
List<T>
that does not have a wrapper class
With the help of the links above, I'm able to solve each of the two problems individually - either deserialize to a List<BaseClass>
without a wrapper class (but then it ignores the derived classes and only restores instances of the base class), or deserialize all derived classes properly, but with a help of a dummy wrapper class:
[XmlRoot("dummy")]
public class StupidWrapperNotWanted
{
[XmlArrayItem("BaseClass", typeof(BaseClass))]
[XmlArrayItem("Derived1", typeof(Derived1))]
[XmlArrayItem("Derived2", typeof(Derived2))]
public List<BaseClass> ListOfThings { get; set; }
}
which also requires wrapping the XML I have into a <dummy></dummy>
.
But when I try to combine the two solutions and attach the [XmlArrayItem]
attributes to the list with AttributeOverrides
:
var overrides = new XmlAttributeOverrides();
var attrs = new XmlAttributes();
attrs.XmlArrayItems.Add(new XmlArrayItemAttribute("BaseClass", typeof(BaseClass)));
attrs.XmlArrayItems.Add(new XmlArrayItemAttribute("Derived1", typeof(Derived1)));
attrs.XmlArrayItems.Add(new XmlArrayItemAttribute("Derived2", typeof(Derived2)));
overrides.Add(typeof(List<BaseClass>), attrs);
var serializer = new XmlSerializer(typeof(List<BaseClass>), overrides, null, new XmlRootAttribute("ListOfThings"), "");
, I get an error on the = new XmlSerializer
line:
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Xml.dll
Additional information: There was an error reflecting type 'System.Collections.Generic.List`1[ConsoleApplication1.BaseClass]'.
What have I done wrong and how do I make it work?