linq to xml仅选择具有特定元素的节点

时间:2012-03-06 10:44:17

标签: c# linq-to-xml

使用以下xml我只想返回<category domain="Portal Sub" value="Events">节点中有子元素的项目。

我尝试使用以下代码,但它仍然返回所有节点。 任何帮助将不胜感激,因为我似乎无法弄清楚如何只获得子节点所在的项目。

  <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();

1 个答案:

答案 0 :(得分:1)

from item in xdoc.Descendants("item")
where item.Descendants("category").Any(c => (string)c.Attribute("domain") == "Portal"
  && (string)c.Attribute("value") == "Events" && c.Elements().Any())
select ...