Linq to XML嵌套查询

5

我有一个关于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循环对我来说有点混乱。
谢谢
2个回答

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
  }

基本思路是在设备(一个Descendant)上进行一种“子选择”,寻找其中包含的所有Interface元素。

它为每个设备下的“接口”创建一个新的DeviceInterface


谢谢,看起来好多了,我稍后会试一下 :) - user299342

1

快速而简单

var query = from device in document.Descendants("device")
            select new
            {
                ID = device.Attribute("id").Value,
                Name = device.Attribute("name").Value,
                Interfaces = from deviceInterface in device.Descendants("interface")
                             select new
                             {
                                 ID = deviceInterface.Attribute("id").Value,
                                 Description = deviceInterface.Attribute("description")
                             }
            };

你仍然需要迭代query来创建(或填充)一个List<Device>(请参见发布的代码中的lsDevices)。 - Alex Bagnolini

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接