3

I got an XML structure like:

<siteNode controller="a" action="b" title="">
  <siteNode controller="aa" action="bb" title="" />
  <siteNode controller="cc" action="dd" title="">
    <siteNode controller="eee" action="fff" title="" />
  </siteNode>
</siteNode>

From C# Linq to XML, get parents when a child satisfy condition

I got something like this:

XElement doc = XElement.Load("path");
var result = doc.Elements("siteNode").Where(parent =>
  parent.Elements("siteNode").Any(child => child.Attribute("action").Value ==
  ActionName && child.Attribute("controller").Value == ControlerName));

Which returns my node and its parent. How could I get not only the parent of the node but also its "grandparents", I mean the parent of the parent etc. So with my XML it would be:

<siteNode controller="eee" action="fff" title="" /> 
with parent 
<siteNode controller="cc" action="dd" title="" >
with parent
<siteNode controller="a" action="b" title="" >

Obvious answer is to use that linq expression on found parent until it's null, but is there any better (cleaner) way?

Community
  • 1
  • 1
user1291518
  • 89
  • 1
  • 8

1 Answers1

5

AncestorsAndSelf method does exactly what you need, it finds ancestors of an element on all parent levels. Descendants method finds elements by name at any level and FirstOrDefault method returns first element that matches criteria or null if no matching element is found:

    XElement el = doc.Descendants("siteNode")
                    .FirstOrDefault(child => 
                        child.Attribute("action").Value == ActionName 
                        && 
                        child.Attribute("controller").Value == ControlerName);
    if (el != null)
    {
        var result2 = el.AncestorsAndSelf();
    }
Ivan Golović
  • 8,732
  • 3
  • 25
  • 31