Linq to XML 嵌套查询
我在使用 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 循环对我来说似乎有点混乱
干杯
I'm having an issue getting a LINQ query to work. I have this 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>
And this code:
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);
}
My Device object contains a List of DeviceInterfaces which I need to populate from the XML. At the moment my code only populates the first interface, any subsequent ones are ignored and I can't understand why.
I'd also appreciate any comments on whether or not this is the right way to do it. The nested foreach loops seem a bit messy to me
Cheers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里的基本点是,您在设备(它是
后代
)上执行某种“子选择”,查找它包含的所有Interface
元素。它为每个设备下的每个“接口”创建一个新的
DeviceInterface
。The basic point here is that you do a sort of "subselect" on device (which is a
Descendant
), seeking all theInterface
elements that it contains.It creates a new
DeviceInterface
for each "interface" under each device.又快又脏
Quick and dirty