C#XML,查找node及其所有父节点

C#XML,查找node及其所有父节点,c#,xml,linq,C#,Xml,Linq,我得到了如下XML结构: <siteNode controller="a" action="b" title=""> <siteNode controller="aa" action="bb" title="" /> <siteNode controller="cc" action="dd" title=""> <siteNode controller="eee" action="fff" title="" /> </si

我得到了如下XML结构:

<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>
返回我的节点及其父节点。如何不仅获取节点的父节点,还获取其“祖父母”,我指的是父节点的父节点等。因此,使用我的XML,它将是:

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

与父母
与父母

显然,答案是在找到的父级上使用linq表达式,直到它为null,但有没有更好的(更干净的)方法?

AnteStorsandSelf方法正是根据您的需要,它在所有父级上查找元素的祖先。后代方法在任何级别按名称查找元素,FirstOrDefault方法返回与条件匹配的第一个元素,如果未找到匹配的元素,则返回null:

    XElement el = doc.Descendants("siteNode")
                    .FirstOrDefault(child => 
                        child.Attribute("action").Value == ActionName 
                        && 
                        child.Attribute("controller").Value == ControlerName);
    if (el != null)
    {
        var result2 = el.AncestorsAndSelf();
    }
    XElement el = doc.Descendants("siteNode")
                    .FirstOrDefault(child => 
                        child.Attribute("action").Value == ActionName 
                        && 
                        child.Attribute("controller").Value == ControlerName);
    if (el != null)
    {
        var result2 = el.AncestorsAndSelf();
    }