我正在尝试序列化我的对象,但是如果没有列表的根名称我就无法序列化它。集线器,交换机和设备是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&PID_0000"/>
<Switch Tag="SWITCH1" />
<Device Tag="MOUSE" VidPid="VID_0000&PID_0000"/>
</DevicesList>
</RootHub>
但我需要的是:
<RootHub>
<Hub20 Tag="HUB1" VidPid="VID_0000&PID_0000"/>
<Switch Tag="SWITCH1" />
<Device Tag="MOUSE" VidPid="VID_0000&PID_0000"/>
</RootHub>
我已经尝试过这个问题Getting rid of an array name in C# XML Serialization的解决方案,但它不起作用,因为无法将XmlArrayItem与XmlElement属性混合使用。还有其他办法吗?
答案 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; }