0
使用以下xml我只想返回<category domain="Portal Sub" value="Events">
節點中存在子元素的項目。linq to xml只選擇具有特定元素的節點
我試着用下面的代碼,但它仍然返回所有節點。 任何幫助將不勝感激,因爲我似乎無法弄清楚如何獲得只有子節點存在的項目。
<item guid="123">
<title>test1</title>
<category domain="Target">Business Decision Makers</category>
<category domain="Target">Individual Customers</category>
<category domain="Target">IT Decision Makers</category>
<category domain="Portal" value="IT Network">
<category domain="Portal Sub" value="Events">
<category domain="Portal Sub" value="Forum" />
</category>
</category>
</item>
<item guid="456">
<title>test2</title>
<category domain="Target">IT managers</category>
<category domain="Target">IT Professional</category>
<category domain="Portal" value="IT Network">
<category domain="Portal Sub" value="Events" />
</category>
</item>
var getFilteredItems = (from item in xdoc.Descendants("item")
where item.Descendants("category").Descendants("category").Any()
select new
{
etype = (from x in item.Elements("category").Elements("category")
where x.Attribute("value").Value == "Events"
select new
{
cctype = x.Descendants("category").Select(i => i.Attribute("value").Value ?? "")
}).First()
}).ToList();
感謝馬丁,完美。我玩弄了屬性值,但錯過了Elements.Any部分。感謝您的快速幫助! – 2012-03-06 11:24:01