简体   繁体   中英

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?

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.

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM