我收到类似于此的XML片段:
<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>
我有一组相应的课程:
public class BaseClass {...}
public class Derived1 : BaseClass {...}
public class Derived2 : BaseClass {...}
和我想将XML片段反序列化为List<BaseClass>
。
实际上我想一次解决两个问题:
List<T>
that does not have a wrapper class 借助上面的链接,我可以单独解决这两个问题中的每一个 - 在没有包装类的情况下反序列化为List<BaseClass>
(但是它会忽略派生类并且只恢复实例基类),或正确反序列化所有派生类,但借助虚拟包装类:
[XmlRoot("dummy")]
public class StupidWrapperNotWanted
{
[XmlArrayItem("BaseClass", typeof(BaseClass))]
[XmlArrayItem("Derived1", typeof(Derived1))]
[XmlArrayItem("Derived2", typeof(Derived2))]
public List<BaseClass> ListOfThings { get; set; }
}
还需要将我拥有的XML包装到<dummy></dummy>
。
但是,当我尝试将两个解决方案合并并使用[XmlArrayItem]
将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"), "");
,我在= new XmlSerializer
行收到错误:
System.Xml.dll中出现未处理的“System.InvalidOperationException”类型异常
其他信息:出现错误,反映出类型为'System.Collections.Generic.List`1 [ConsoleApplication1.BaseClass]'。
我做错了什么以及如何使其发挥作用?