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.
Provide different names for items of different types:
[XmlElement("derivedA", typeof(DerivedClassA))]
[XmlElement("derivedB", typeof(DerivedClassB))]
public List<AbstractClass> list { get; set; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.