我有一個問題讓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循環似乎有點亂給我
乾杯
感謝,看起來好多了,我給它一個鏡頭後:) – user299342 2010-03-23 10:29:03
沒錯這點上,乾杯! – user299342 2010-03-23 18:18:31