我的 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));
返回我的节点及其父节点。我怎样才能不仅得到节点的父节点,而且还得到它的“祖 parent ”,我的意思是父节点的父节点等等。所以对于我的 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,但是有没有更好(更干净)的方法?
最佳答案
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();
}
关于C# XML,查找节点及其所有父节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11412029/