简体   繁体   中英

LINQ to XML - parent's attribute in where clause

I'm having troubles with this where clause;

from item in 
_documentRoot.Descendants("Level1").Descendants("Level2").Descendants("Level3")
where
_documentRoot.Descendants("Level1").Descendants("Level2").Attributes("id").First().Value == 12345

I want a list of Level3 items from the Level2 element that has an id of 12345.

as always, many thanks

I would go with XPath here:

var items = xdoc.XPathSelectElements("//Level1/Level2[@id='1234']/Level3");

It selects all Level3 items from Level2 item(s) which have attribute id equal to 1234. With LINQ method syntax it will look like:

var items = xdoc.Descendants("Level1")
                .Elements("Level2")
                .Where(l2 => (string)l2.Attribute("id") == "1234")
                .SelectMany(l2 => l2.Elements("Level3"));

Something like this (it's untested):

from item in _documentRoot.Descendants("Level1").Descendants("Level2")
where item.Attributes("id").First().Value == "1234"
select item.Descendants("Level3")
var res = from item
in _documentRoot.Descendants("Level1").Descendants("Level2")
where item.Attributes("id").First().Value == "12345"
select item.Descendants("Level3");
_documentRoot.Descendants("Level1")
             .Descendants("Level2")
             .Where(i => i.Attributes.Any(a => a.Value == "1234"))
             .SelectMany(i => i.Descendants("Level3"));

The .SelectMany extenstion method is important to concatenate all the Level3 descendents into one IEnumerable

In case there could be some issues with id attribute.

_root.Descendants("Level1")
     .Elements("Level2")
     .Where(T => T.Attributes("id").Any(W => W.Value == "12345"))
     .Elements("Level3");
var res = from x in _documentRoot.Descendants("Level1").Descendants("Level2")
where x.Attributes("ID").FirstOrDefault(id=> id.Value=="12345") != null
select x.Descendants("Level3");

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