我想序列化包含List<AbstractClass>
和DerivedClassA
的{{1}},其中这两个类都来自DerivedClassB
。
此外,我想向包含列表中每个元素的元素添加一个属性。我想要的输出是这样的:
AbstractClass
到目前为止我所拥有的是:
<MyCustomListName foo="bar">
<DerivedClassA baseAttribute="value" attributeFromA="value"/>
<DerivedClassB baseAttribute="value" attributeFromB="value"/>
...
</MyCustomListName>
使用它,我得到以下输出:
public class MyCustomListName
{
[XmlAttribute]
public string foo {get; set;}
[XmlArray]
public List<AbstractClass> list { get; set; }
}
[XmlInclude(typeof(DerivedClassA))]
[XmlInclude(typeof(DerivedClassB))]
public abstract class AbstractClass
{
[XmlAttribute]
public string baseAttribute {get; set;}
}
public class DerivedClassA : AbstractClass
{
[XmlAttribute]
public string attributeFromA {get; set;}
}
public class DerivedClassB : AbstractClass
{
[XmlAttribute]
public string attributeFromB {get; set;}
}
因此,要获得所需的输出,应该没有嵌套的<MyCustomListName foo="bar">
<list>
<AbstractClass xsi:type="DerivedClassA" baseAttribute="value" attributeFromA="value"/>
<AbstractClass xsi:type="DerivedClassB" baseAttribute="value" attributeFromB="value"/>
</list>
</MyCustomListName>
元素,而不是<list>
属性,元素名称应为xsi:type
或DerivedClassA
,具体取决于关于类型。
答案 0 :(得分:3)
为不同类型的项目提供不同的名称:
[XmlElement("derivedA", typeof(DerivedClassA))]
[XmlElement("derivedB", typeof(DerivedClassB))]
public List<AbstractClass> list { get; set; }