[英]Linq to XML nested query
我在使用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循環對我來說似乎有點亂
干杯
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
}
這里的基本點是你在設備上做一種“subselect”(它是一個Descendant
),尋找它包含的所有Interface
元素。
它為每個設備下的每個“接口”創建一個新的DeviceInterface
。
又臟又臟
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")
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.