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

x
  • 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
          </Menu>
    </Menu>
</Menu>

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

Cheers.


0
smacca
Asked:
smacca
1 Solution
 
b1xml2Commented:
using System.Xml;

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

}


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

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