我正在尝试生成 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>
我正在考虑使用这样的东西:
[XmlArray( "device_list" ), XmlArrayItem("item")]
public ListItem[] device_list { get; set; }
作为属性,使用此类声明:
public class ListItem {
[XmlAttribute]
public string type { get; set; }
[XmlText]
public string Value { get; set; }
}
这给了我内部序列化,但我不知道如何将 type="list"
属性应用于上面的 device_list
。
我在想(但不确定如何编写语法)我需要做一个:
public class DeviceList {
[XmlAttribute]
public string type { get; set; }
[XmlArray]
public ListItem[] .... This is where I get lost
}
根据 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; }
}
目前的用法是:
[XmlArray( "device_list" ), XmlArrayItem("item")]
public DeviceList device_list { get; set; }
和类型,在代码中声明如下:
device_list = new DeviceList{type = "list"}
device_list.Add( new ListItem { type = "MAC", Value = "1234566" } );
device_list.Add( new ListItem { type = "MAC", Value = "1234566" } );
不显示序列化类型。这是序列化的结果:
<device_list>
<item type="MAC">1234566</item>
<item type="MAC">1234566</item>
</device_list>
所以显然我仍然缺少一些东西......
最佳答案
使用上面 Dave 的部分回答,我发现最好像这样在声明类中使用属性:(注意缺少属性)
public DeviceList device_list { get; set; }
然后像这样更新 DeviceList 类:
[XmlType("device_list")]
[Serializable]
public class DeviceList {
[XmlAttribute]
public string type { get; set; }
[XmlElement( "item" )]
public ListItem[] items { get; set; }
}
并保留原来的ListItem类
public class ListItem {
[XmlAttribute]
public string type { get; set; }
[XmlText]
public string Value { get; set; }
}
我的序列化符合预期:
<device_list type="list">
<item type="MAC">1234567</item>
<item type="MAC">123456890</item>
</device_list>
关于c# - 如何在 C# 序列化期间为数组赋予属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8790807/