我有一个关于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);
}
我的Device对象包含一个DeviceInterfaces列表,我需要从XML中填充它。目前我的代码只填充第一个接口,任何后续的都被忽略了,我不明白为什么。
我也希望得到关于这是否是正确的方法的任何评论。嵌套的foreach循环对我来说有点混乱。
谢谢