views:

494

answers:

2

any node above the current node in an hierarchical tree example the parent,grandparent,great-grandparent or the rot node are all ancestors of anode within an xml

How might I get the grand parent and great grand parent of a current node xml.

I'm using VB.Net in an ASP.NET application.

thank wow answers are beautiful

can i have something like XmlNode greatGrandParent = myNode.ParentNode.ParentNode.ParentNode.lastchild.lastchild

+3  A: 

Using the System.Xml the XmlNode has a ParentNode property so you could use that to traverse up the tree.

Using the System.Xml.XPath the XPathNavigator has a MoveToParent method.

Using System.Xml.Linq the XNode class has an Ancestors method which can be a bit neater:-

GrandParent = Node.Ancestors.Skip(1).Single()
GreatGrandParent = Node.Ancestors.Skip(2).Single()
AnthonyWJones
+3  A: 

In (the dim) light of the very limited information provided, I would only suggest that you use the ParentNode property of the context XmlNode object.

eg. Get Grandparent:

XmlNode grandParent = myNode.ParentNode.ParentNode;

eg. Get Grandparent:

XmlNode greatGrandParent = myNode.ParentNode.ParentNode.ParentNode;

Note that this is prone to exceptions. For instance, if the current node does not have a ParentNode (or is of the type - Attribute, Document, DocumentFragment, Entity, Notation), then the code will throw an exception because such nodes cannot have Parents.

Please edit your question to provide more information so that answers can be "better".

Cerebrus
dude u are soo right ,dot on the spot
Spikie
can i have something like lastchild.lastchild stuff like that
Spikie
???????????????????
Spikie
@Spikie: Your question mark key seems to stick. Maybe it's time for a new keyboard.
Tomalak
yeah dude i have this old dell keyboard that is driving me crazy u no any good "CHEAP" keyboard !
Spikie
@Spikie: Thanks for the vote, etc. I wish this question hadn't been Community Wiki. Would have helped my vote target. ;-)
Cerebrus