[英]C# XML Serializing list with element name depending on class
I want to serialize a List<AbstractClass>
that contains DerivedClassA
and DerivedClassB
where both of these classes are derived from AbstractClass
. 我想序列化包含
DerivedClassA
和DerivedClassB
的List<AbstractClass>
,其中这两个类都是从AbstractClass
派生的。
Additionally I want to add an attribute to the element that wraps each element of the list. 另外,我想向包裹列表中每个元素的元素添加一个属性。 My desired output is something like this:
我想要的输出是这样的:
<MyCustomListName foo="bar">
<DerivedClassA baseAttribute="value" attributeFromA="value"/>
<DerivedClassB baseAttribute="value" attributeFromB="value"/>
...
</MyCustomListName>
What I have so far is this: 我到目前为止所拥有的是:
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;}
}
Using this, I get the following output: 使用这个,我得到以下输出:
<MyCustomListName foo="bar">
<list>
<AbstractClass xsi:type="DerivedClassA" baseAttribute="value" attributeFromA="value"/>
<AbstractClass xsi:type="DerivedClassB" baseAttribute="value" attributeFromB="value"/>
</list>
</MyCustomListName>
So, to get my desired output, there should be no nested <list>
element and instead of the xsi:type
attribute, the element name should be DerivedClassA
or DerivedClassB
depending on the type. 因此,要获得所需的输出,应该没有嵌套的
<list>
元素,并且取决于xsi:type
,该元素的名称应为DerivedClassA
或DerivedClassB
而不是xsi:type
属性。
Provide different names for items of different types: 为不同类型的项目提供不同的名称:
[XmlElement("derivedA", typeof(DerivedClassA))]
[XmlElement("derivedB", typeof(DerivedClassB))]
public List<AbstractClass> list { get; set; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.