6

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?

7
  • Can number of Device can be more than one? Commented Feb 14, 2015 at 21:07
  • Yes, there can be multiple Hub20, Switches, Devices. Commented Feb 14, 2015 at 21:17
  • What does your DevicesList class look like? Commented Feb 14, 2015 at 21:21
  • It's not a class, its just list of AbstractNode objects. Each device is dervied from that class. Commented Feb 14, 2015 at 21:22
  • I am sorry, I mean AbstractNode class Commented Feb 14, 2015 at 21:24

1 Answer 1

9

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; }
Sign up to request clarification or add additional context in comments.

3 Comments

Wow thank man. I can't believe in such easy solution. I've lost countless time trying to find way, including custom serialization using IXmlSerializable without any results...
What about using class instead of List? Like Money Price {get; set;}. Money has Amount and Currency properties. Can we serialize an object like this way? It does not work in same way. Any other suggestion?
@ahmet your question doesn't seem at all related to the OP's question. You should post a new question, not a comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.