2010-03-22 216 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