3

我有一个 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 到 XML,当孩子满足条件时获取父母

我得到了这样的东西:

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 表达式,直到它为空,但有没有更好(更清洁)的方法?

4

1 回答 1

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();
    }
于 2012-07-10T11:21:48.700 回答