我在使用 LINQ 查询时遇到问题。我有这个 XML:
<devices>
<device id ="2142" name="data-switch-01">
<interface id ="2148" description ="Po1"/>
</device>
<device id ="2302" name="data-switch-02">
<interface id ="2354" description ="Po1"/>
<interface id ="2348" description ="Gi0/44" />
</device>
</devices>
这段代码:
var devices = from device in myXML.Descendants("device")
select new
{
ID = device.Attribute("id").Value,
Name = device.Attribute("name").Value,
};
foreach (var device in devices)
{
Device d = new Device(Convert.ToInt32(device.ID), device.Name);
var vIfs = from vIf in myXML.Descendants("device")
where Convert.ToInt32(vIf.Attribute("id").Value) == d.Id
select new
{
ID = vIf.Element("interface").Attribute("id").Value,
Description = vIf.Element("interface").Attribute("description").Value,
};
foreach (var vIf in vIfs)
{
DeviceInterface di = new DeviceInterface(Convert.ToInt32(vIf.ID), vIf.Description);
d.Interfaces.Add(di);
}
lsDevices.Add(d);
}
我的设备对象包含我需要从 XML 填充的设备接口列表。目前我的代码仅填充第一个界面,任何后续界面都会被忽略,我不明白为什么。
我也很感激任何关于这是否是正确方法的评论。嵌套的 foreach 循环对我来说似乎有点混乱
Cheers
IEnumerable<Device> devices =
from device in myXML.Descendants("device")
select new Device(device.Attribute("id").Value, device.Attribute("name").Value)
{
Interfaces = (from interface in device.Elements("Interface")
select new DeviceInterface(
interface.Attribute("id").Value,
interface.Attribute("description").Value)
).ToList() //or Array as you prefer
}
这里的基本点是,您在设备上执行某种“子选择”(这是一个Descendant
),求所有的Interface
它包含的元素。
它创造了一个新的DeviceInterface
对于每个设备下的每个“接口”。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)