C# XML Serializing list with element name depending on class

怎甘沉沦 提交于 2021-01-28 00:41:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!