问题
I want to serialize a List<AbstractClass>
that contains DerivedClassA
and DerivedClassB
where both of these classes are derived from 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.
回答1:
Provide different names for items of different types:
[XmlElement("derivedA", typeof(DerivedClassA))]
[XmlElement("derivedB", typeof(DerivedClassB))]
public List<AbstractClass> list { get; set; }
来源:https://stackoverflow.com/questions/41676736/c-sharp-xml-serializing-list-with-element-name-depending-on-class