2010-03-22 179 views
5

我有一个问题让LINQ查询工作。我有这样的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填充DeviceInterfaces的名单。目前我的代码只填充第一个接口,后面的接口都被忽略,我不明白为什么。

我也很感激任何意见,这是否是正确的方式来做到这一点。嵌套foreach循环似乎有点乱给我

干杯

回答

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 
    } 

这里最基本的一点是,你做的一种“再选择”设备上(这是一个​​),求所有Interface元素它包含。

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

+0

感谢,看起来好多了,我给它一个镜头后:) – user299342 2010-03-23 10:29:03

+0

没错这点上,干杯! – user299342 2010-03-23 18:18:31

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") 
          } 
      }; 
+0

您仍然需要迭代'query'来创建(或填充)'List '(请参阅发布的代码中的'lsDevices')。 – 2010-03-22 20:50:53