简体   繁体   中英

linq to xml Select only nodes that have certain elements

With the following xml I only want to return the items where there is a child element in the <category domain="Portal Sub" value="Events"> node.

I tried with the following code but it still returns all nodes. Any help would be appreciated as I can't seem to figure out how to get only the items where a child node is present.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM