Linq to XML selects descendants of descendants, each with a specific attribute
I've found many articles on how to get a descendant with a specific attribute, but I can't seem to find anything when selecting multiple descendants with different attributes with LINQ to XML. So from the next example I need to select all grandchildren where Parent name = Ken AND Child name = Lorna
. Potentially, I need to have up to 4 AND
sentences since my real XML is deeper than the example below.
I can code a selection of all children Ken
, but cannot find an example to go deeper.
Any help is appreciated
<?xml version="1.0" encoding="UTF-8"?>
<FamilyTree>
<Parent name="Ken">
<Child name="Lorna">
<Grandchild name="Andrew"/>
<Grandchild name="Brian"/>
</Child>
<Child name="Mike">
<Grandchild name="Ann"/>
<Grandchild name="Beth"/>
</Child>
</Parent>
<Parent name="Norma">
<Child name="Owen">
<Grandchild name="Charles"/>
</Child>
<Child name="Peter">
<Grandchild name="Charlotte"/>
</Child>
</Parent>
<Parent name="Quinn">
<Child name="Robert">
<Grandchild name="Debbie"/>
<Grandchild name="Eric"/>
</Child>
<Child name="Susan">
<Grandchild name="Frank"/>
</Child>
</Parent>
</FamilyTree>
source to share
There are several options here, but I would suggest the simplest thing to just check each grandchild:
var grandchildren = doc
.Descendants("Grandchild")
.Where(x => (string) x.Parent.Parent.Attribute("name") == "Ken" &&
(string) x.Parent.Attribute("name") == "Lorna");
Or, you can find all matching elements Child
and then get their children:
var grandchildren = doc
.Descendants("Child")
.Where(x => (string) x.Parent.Attribute("name") == "Ken" &&
(string) x.Attribute("name") == "Lorna")
.Elements("Grandchild");
source to share