Linq to XML嵌套查询

use*_*342 5 c# 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>
Run Code Online (Sandbox Code Playgroud)

这段代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

我的Device对象包含一个DeviceInterfaces列表,我需要从XML中填充它.目前我的代码只填充第一个界面,任何后续界面都会被忽略,我无法理解为什么.

我也很感激任何关于这是否是正确方法的评论.嵌套的foreach循环对我来说似乎有点乱

干杯

Ale*_*ini 12

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
  }
Run Code Online (Sandbox Code Playgroud)

这里的基本点是你在设备上做一种"subselect"(它是a Descendant),寻找Interface它包含的所有元素.

DeviceInterface为每个设备下的每个"接口" 创建一个新的.