How do I give an array an attribute during serialization in C#?

jcolebrand picture jcolebrand · Jan 9, 2012 · Viewed 9.4k times · Source

I'm trying to generate C# that creates a fragment of XML like this.

<device_list type="list">
    <item type="MAC">11:22:33:44:55:66:77:88</item>
    <item type="MAC">11:22:33:44:55:66:77:89</item>
    <item type="MAC">11:22:33:44:55:66:77:8A</item>
</device_list>

I was thinking of using something like this:

[XmlArray( "device_list" ), XmlArrayItem("item")]
public ListItem[] device_list { get; set; }

as the property, with this class declaration:

public class ListItem {
    [XmlAttribute]
    public string type { get; set; }

    [XmlText]
    public string Value { get; set; }
}

Which gives me the inner serialization, but I don't know how to apply the type="list" attribute to the device_list above.

I'm thinking (but not sure of how to write the syntax) that I need to do a:

public class DeviceList {
    [XmlAttribute]
    public string type { get; set; }

    [XmlArray]
    public ListItem[] .... This is where I get lost
}

Updated based on Dave's responses

public class DeviceList : List<ListItem> {
    [XmlAttribute]
    public string type { get; set; }
}

public class ListItem {
    [XmlAttribute]
    public string type { get; set; }

    [XmlText]
    public string Value { get; set; }
}

and the usage is currently:

[XmlArray( "device_list" ), XmlArrayItem("item")]
public DeviceList device_list { get; set; }

And the type, while being declared in the code like thus:

device_list = new DeviceList{type = "list"}
device_list.Add( new ListItem { type = "MAC", Value = "1234566" } );
device_list.Add( new ListItem { type = "MAC", Value = "1234566" } );

Isn't showing the type on serialization. This is the result of the serialization:

<device_list>
  <item type="MAC">1234566</item>
  <item type="MAC">1234566</item>
</device_list>

So apparently I'm still missing something...

Answer

jcolebrand picture jcolebrand · Jan 9, 2012

Using part of Dave's answer above, I found that it was best to use the property in the declaring class like this: (note the lack of attributes)

public DeviceList device_list { get; set; }

and then update the DeviceList class like this:

[XmlType("device_list")]
[Serializable]
public class DeviceList {
    [XmlAttribute]
    public string type { get; set; }

    [XmlElement( "item" )]
    public ListItem[] items { get; set; }
}

and keep the original ListItem class

public class ListItem {
    [XmlAttribute]
    public string type { get; set; }

    [XmlText]
    public string Value { get; set; }
}

and my serialization is as expected:

<device_list type="list">
  <item type="MAC">1234567</item>
  <item type="MAC">123456890</item>
</device_list>