C# XML 序列化列表,元素名称取决于类 [英] C# XML Serializing list with element name depending on class

查看:22
本文介绍了C# XML 序列化列表,元素名称取决于类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想序列化一个包含 DerivedClassADerivedClassBList,其中这两个类都是从 AbstractClass 派生的.

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>

所以,为了得到我想要的输出,不应该有嵌套的 元素,而不是 xsi:type 属性,元素名称应该是 DerivedClassADerivedClassB 取决于类型.

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; }

这篇关于C# XML 序列化列表,元素名称取决于类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆