Marduk
Marduk

Reputation: 389

Serialize into XML a list with multiple types without root element name

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&amp;PID_0000"/>
      <Switch Tag="SWITCH1" />
      <Device Tag="MOUSE" VidPid="VID_0000&amp;PID_0000"/>
   </DevicesList>
</RootHub>

But what I need is this:

<RootHub>
   <Hub20 Tag="HUB1" VidPid="VID_0000&amp;PID_0000"/>
   <Switch Tag="SWITCH1" />
   <Device Tag="MOUSE" VidPid="VID_0000&amp;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?

Upvotes: 6

Views: 3002

Answers (1)

Thomas Levesque
Thomas Levesque

Reputation: 292405

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

Upvotes: 9

Related Questions