[英]C# XML Serializing list with element name depending on class
我想序列化包含DerivedClassA
和DerivedClassB
的List<AbstractClass>
,其中這兩個類都是從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
或DerivedClassB
而不是xsi:type
屬性。
為不同類型的項目提供不同的名稱:
[XmlElement("derivedA", typeof(DerivedClassA))]
[XmlElement("derivedB", typeof(DerivedClassB))]
public List<AbstractClass> list { get; set; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.