2

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:

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?

Community
  • 1
  • 1
GSerg
  • 76,472
  • 17
  • 159
  • 346
  • 2
    The reason you cannot apply an override `XmlArrayItemAttribute` to `List` is explained in [Constructor of a XmlSerializer serializing a `List` throws an InvalidOperationException when used with XmlAttributeOverrides](https://stackoverflow.com/q/47119999/3744182). In that case there was a workaround of overriding `XmlRoot` and `XmlType` for the collection element's type, but in your case you really need to apply `XmlArrayItem` so that won't work. I think you're going to need to use a `StupidWrapperNotWanted`. – dbc Feb 27 '18 at 18:39

0 Answers0