将包含多个类型但没有根元素名称的列表序列化为XML

时间:2015-02-14 21:04:36

标签: c# xml serialization

我正在尝试序列化我的对象,但是如果没有列表的根名称我就无法序列化它。集线器,交换机和设备是AbstractNode的派生类型。

[XmlRoot(ElementName = "Roothub")]
public class RootHub
{
    [XmlArrayItem(typeof(Hub), ElementName = "Hub20")]
    [XmlArrayItem(typeof(Switch), ElementName = "Switch")]
    [XmlArrayItem(typeof(Device), ElementName = "Device")]
    public List<AbstractNode> DevicesList { get; set; }
}

[XmlInclude(typeof(Hub))]
[XmlInclude(typeof(Device))]
[XmlInclude(typeof(Switch))]

public abstract class AbstractNode
{
    [XmlAttribute]
    public string Tag { get; set; }
}

输出:

<RootHub>
   <DevicesList>
      <Hub20 Tag="HUB1" VidPid="VID_0000&amp;PID_0000"/>
      <Switch Tag="SWITCH1" />
      <Device Tag="MOUSE" VidPid="VID_0000&amp;PID_0000"/>
   </DevicesList>
</RootHub>

但我需要的是:

<RootHub>
   <Hub20 Tag="HUB1" VidPid="VID_0000&amp;PID_0000"/>
   <Switch Tag="SWITCH1" />
   <Device Tag="MOUSE" VidPid="VID_0000&amp;PID_0000"/>
</RootHub>

我已经尝试过这个问题Getting rid of an array name in C# XML Serialization的解决方案,但它不起作用,因为无法将XmlArrayItem与XmlElement属性混合使用。还有其他办法吗?

1 个答案:

答案 0 :(得分:4)

使用XmlElement属性代替XmlArrayItem,它会为您提供所需的输出。

[XmlElement(typeof(Hub), ElementName = "Hub20")]
[XmlElement(typeof(Switch), ElementName = "Switch")]
[XmlElement(typeof(Device), ElementName = "Device")]
public List<AbstractNode> DevicesList { get; set; }