我有一个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>
Run Code Online (Sandbox Code Playgroud)
我有这样的事情:
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));
Run Code Online (Sandbox Code Playgroud)
哪个返回我的节点及其父节点.我怎么能不仅获得节点的父节点而且还获得它的"祖父母",我的意思是父节点的父节点等.因此,使用我的XML,它将是:
<siteNode controller="eee" action="fff" title="" />
with parent
<siteNode controller="cc" action="dd" title="" >
with parent
<siteNode controller="a" action="b" title="" >
Run Code Online (Sandbox Code Playgroud)
明显的答案是在找到的父项上使用该linq表达式,直到它为空,但有没有更好(更清洁)的方法?
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();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5907 次 |
最近记录: |