[英]How to get all parents for a given child node?
<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 controller="eee1" action="fff1" title="" />
</siteNode>
</siteNode>
How can I get parents of a child node using LINQ? 如何使用LINQ获取子节点的父母?
For instance, if I gave the controller="eee"
element, I would get back: 例如,如果我给了
controller="eee"
元素,我会回来的:
<siteNode controller="a" action="b" title="">
<siteNode controller="aa" action="bb" title="" />
<siteNode controller="cc" action="dd" title="">
I need to get all parent and grand parent nodes from the above sample. 我需要从上述示例中获取所有父节点和祖父节点。
You mean like this? 你的意思是这样吗?
IEnumerable<XElement> GetParents(XElement element)
{
XElement cParent = element.Parent;
while (cParent != null)
{
yield return cParent;
cParent = cParent.Parent;
}
}
Edit: 编辑:
As Jeff pointed out in a comment, your example actually did have a closing tag on one of your "parent" rows, and thus should not have actually been included. 正如Jeff在评论中指出的那样,您的示例实际上在您的“父”行之一上有一个结束标记,因此实际上不应包含在内。 If you actually meant "elements that fall before the given record, " as compared to its parents , you can use
XNode.NodesBeforeSelf()
. 如果您的实际意思是与其父元素相比“属于给定记录的元素”,则可以使用
XNode.NodesBeforeSelf()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.