I have found many articles on getting a descendant with a specific attribute, but I can't seem to find anything on selecting multiple descendants with different attributes with LINQ to XML. So from the following example, I need to select all the Grandchildren where Parent name = Ken AND Child name = Lorna
. Potentially, I need to have up to 4 AND
clauses as my real XML is deeper than the example below.
I can code selecting all children of Ken
, but can't find an example to go deeper than that.
Any help is greatly 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>
There are multiple options here, but I'd suggest the simplest thing is just to 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 could find all the relevant Child
elements and then retrieves their children:
var grandchildren = doc
.Descendants("Child")
.Where(x => (string) x.Parent.Attribute("name") == "Ken" &&
(string) x.Attribute("name") == "Lorna")
.Elements("Grandchild");
See more on this question at Stackoverflow