Reputation: 511
<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?
For instance, if I gave the controller="eee"
element, I would get back:
<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.
Upvotes: 0
Views: 2057
Reputation: 13286
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. If you actually meant "elements that fall before the given record, " as compared to its parents, you can use XNode.NodesBeforeSelf()
.
Upvotes: 2