如何在C#中序列化期间为数组赋予属性?

jco*_*and 16 c# xml-serialization xml-attribute

我正在尝试生成C#,它会像这样创建一个XML片段.

<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>
Run Code Online (Sandbox Code Playgroud)

我在考虑使用这样的东西:

[XmlArray( "device_list" ), XmlArrayItem("item")]
public ListItem[] device_list { get; set; }
Run Code Online (Sandbox Code Playgroud)

作为属性,具有此类声明:

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

    [XmlText]
    public string Value { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这给了我内部序列化,但我不知道如何将type="list"属性应用于device_list上面.

我正在考虑(但不确定如何编写语法)我需要做的事情:

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

    [XmlArray]
    public ListItem[] .... This is where I get lost
}
Run Code Online (Sandbox Code Playgroud)

根据Dave的回复进行了更新

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; }
}
Run Code Online (Sandbox Code Playgroud)

目前的用途是:

[XmlArray( "device_list" ), XmlArrayItem("item")]
public DeviceList device_list { get; set; }
Run Code Online (Sandbox Code Playgroud)

而类型,虽然在代码中声明如此:

device_list = new DeviceList{type = "list"}
device_list.Add( new ListItem { type = "MAC", Value = "1234566" } );
device_list.Add( new ListItem { type = "MAC", Value = "1234566" } );
Run Code Online (Sandbox Code Playgroud)

没有在序列化上显示类型.这是序列化的结果:

<device_list>
  <item type="MAC">1234566</item>
  <item type="MAC">1234566</item>
</device_list>
Run Code Online (Sandbox Code Playgroud)

所以显然我仍然缺少一些东西......

jco*_*and 12

使用上面Dave的部分答案,我发现最好在声明类中使用这个属性:(注意缺少属性)

public DeviceList device_list { get; set; }
Run Code Online (Sandbox Code Playgroud)

然后像这样更新DeviceList类:

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

    [XmlElement( "item" )]
    public ListItem[] items { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

并保留原始的ListItem类

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

    [XmlText]
    public string Value { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我的序列化是按预期的:

<device_list type="list">
  <item type="MAC">1234567</item>
  <item type="MAC">123456890</item>
</device_list>
Run Code Online (Sandbox Code Playgroud)