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

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>

来自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 表达式上使用它,直到它为 null,但是有没有更好(更干净)的方法呢?

1个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接