Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 284
  • Last Modified:

How to recursively get parent nodes until top of tree is reached?

I have the following XML as example:

<Menu Name="home" Text="Home" NavigateUrl="/tmc" Visible="True" >
     <Menu Name="sites" Text="Control Sites" NavigateUrl="/tmc/sites.aspx" PageTitle="Monitor Control Sites" Visible="True">          
          <Menu Name="br" Text="Brisbane" NavigateUrl="locations.aspx?site=br" Visible="True">

                             ....this can keep going 'n' levels deeper

Now, if I was in the deepest child node in the tree (for example sake), how can I recursively navigate to each parent node (ie parent of current, parent of current, parent of current and so on).


1 Solution
using System.Xml;

public sealed class NodeIterator
      private NodeIterator() {}
      public static XmlNode [] GetNodesArray(XmlNode node)
            ArrayList al = new ArrayList();
            while (node != null)
                  if (node.ParentNode != null && node.ParentNode is XmlElement)
                              node = node.ParentNode;
                              node = null;
            (XmlNode [])return al.ToArray(typeof(XmlNode));


///calling it.
XmlNode [] nodes = NodeIterator.GetNodesArray(doc.SelectSingleNode("//Menu[@NavigateUrl='locations.aspx?site=br']"));

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now