我有一个像这样的XML字符串:
<foo>
...
<barlist id="10">
<bar ... />
<bar ... />
etc..
</barlist>
</foo>
如何将id
barlist
反序列化为对象?
我目前的代码是在没有序列化/反序列化ID的情况下执行此操作:
class FooData{
[XmlArray("barlist")]
[XmlArrayItem("bar",typeof(BarData))]
public List<BarData> Bars;
}
答案 0 :(得分:1)
尝试将XmlAtribute添加到id对象。
更新:我正在添加示例,如何反序列化...
类:
[XmlType(AnonymousType=true)]
[XmlRoot(Namespace="", IsNullable=false)]
public class foo {
[XmlElement("barlist")]
public List<fooBarlist> barlist { get; set; }
}
[XmlType(AnonymousType=true)]
public class fooBarlist {
[XmlElement("bar")]
public List<fooBarlistBar> bar { get; set; }
[XmlAttribute()]
public byte id { get; set; }
}
[XmlType(AnonymousType=true)]
public class fooBarlistBar {
[XmlAttribute()]
public byte number { get; set; }
[XmlAttribute()]
public string value { get; set; }
}
测试xml:
<foo>
<barlist id="1">
<bar number="1" value="Hi" />
<bar number="2" value="Hello" />
</barlist>
<barlist id="2">
<bar number="3" value="Bye" />
<bar number="4" value="Bye bye" />
</barlist>
</foo>
以及将xml反序列化为object的代码:
XmlSerializer serializer = new XmlSerializer(typeof(foo));
XmlReader reader = XmlReader.Create("D:\\test.xml");
foo testObj = serialier.Deserialize(reader) as foo;
然后我们有结果