读取XML用的XDocument
我的类:读取XML用的XDocument
public class Device
{
int ID;
string Name;
List<Function> Functions;
}
和类功能:
public class Function
{
int Number;
string Name;
}
,我有这种结构的XML文件:
<Devices>
<Device Number="58" Name="Default Device" >
<Functions>
<Function Number="1" Name="Default func" />
<Function Number="2" Name="Default func2" />
<Function Number="..." Name="...." />
</Functions>
</Device>
</Devices>
这里是代码,其中我试图阅读对象:
var list = from tmp in document.Element("Devices").Elements("Device")
select new Device()
{
ID = Convert.ToInt32(tmp.Attribute("Number").Value),
Name = tmp.Attribute("Name").Value,
//??????
};
DevicesList.AddRange(list);
我怎么能读“功能” ???
再次做同样的事情,使用Elements
和Select
投射一组元素的对象。
var list = document
.Descendants("Device")
.Select(x => new Device {
ID = (int) x.Attribute("Number"),
Name = (string) x.Attribute("Name"),
Functions = x.Element("Functions")
.Elements("Function")
.Select(f =>
new Function {
Number = (int) f.Attribute("Number"),
Name = (string) f.Attribute("Name")
}).ToList()
});
为清楚起见,其实我建议写在每个Device
和Function
静态FromXElement
方法。然后每一段代码都可以做一件事。因此,例如,Device.FromXElement
可能是这样的:
public static Device FromXElement(XElement element)
{
return new Device
{
ID = (int) element.Attribute("Number"),
Name = (string) element.Attribute("Name"),
Functions = element.Element("Functions").Elements("Function")
.Select(Function.FromXElement)
.ToList();
};
}
这也使您可以在setter方法的类内私有的,所以他们可以(有一点努力周围的集合)公开不变。
感谢我们再次,我会尽量 – 2012-08-06 18:21:48
@乔恩你的意思是“功能”而不是“设备” – Les 2012-08-06 18:50:26
@Les,这并不重要,我意识到) – 2012-08-06 19:28:08
随着你的'Devices'做的一样吗? – Schaliasos 2012-08-06 18:15:08