C#XML,找到节点和他所有的父母

时间:2012-07-10 11:10:31

标签: 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="" />
  </siteNode>
</siteNode>

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

我有这样的事情:

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));

返回我的节点及其父节点。我怎么能不仅获得节点的父节点而且还获得它的“祖父母”,我的意思是父节点的父节点等等。因此,我的XML将是:

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

明显的答案是在找到的父项上使用该linq表达式,直到它为空,但有没有更好(更干净)的方式?

1 个答案:

答案 0 :(得分:5)

AncestorsAndSelf方法完全符合您的需要,它会在所有父级别上找到元素的祖先。 Descendants方法在任何级别按名称查找元素,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();
    }
相关问题