I'm trying to serialize my object below but I cannot serialize it without root name of list. Hub, Switch and Device are derived type from 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; }
}
Output:
<RootHub>
<DevicesList>
<Hub20 Tag="HUB1" VidPid="VID_0000&PID_0000"/>
<Switch Tag="SWITCH1" />
<Device Tag="MOUSE" VidPid="VID_0000&PID_0000"/>
</DevicesList>
</RootHub>
But what I need is this:
<RootHub>
<Hub20 Tag="HUB1" VidPid="VID_0000&PID_0000"/>
<Switch Tag="SWITCH1" />
<Device Tag="MOUSE" VidPid="VID_0000&PID_0000"/>
</RootHub>
I've already tried solution from this question Getting rid of an array name in C# XML Serialization but it won't work because it's not possible to mix XmlArrayItem with XmlElement attributes. Is there other way to do this?
Use the XmlElement
attribute instead of XmlArrayItem
, it will give you the output you want.
[XmlElement(typeof(Hub), ElementName = "Hub20")]
[XmlElement(typeof(Switch), ElementName = "Switch")]
[XmlElement(typeof(Device), ElementName = "Device")]
public List<AbstractNode> DevicesList { get; set; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.