tags:

views:

103

answers:

3

Given:

a xmlnode that you got from calling the XmlDocument.GetSingleNode method, where you know that the node is an element,

if you want to find the simple path to that element, is there something more straightforward than climbing the tree til you get to the root node and buildling the path as you go? Not that that's hard, I just would have expected there's an existing method/property to get back a string representing the path.

I can see that "the simple path" might not be an easy-to-nail-down term, what I mean is the slash-separated list of elements beginning with "/", using the child axis, that leads to the node I have in hand.

Thanks

+1  A: 

I am not aware of a built-in method to do that, and I don't really see the benefit either.

Because identifying a node by its index is not reliable if the document can change, and how would you identify it in a generic way otherwise? If you want to keep a runtime pointer to a node on a document which does not change, you don't need to traverse the tree to find it since you can just keep a XPathNavigator to it or a reference to XmlElement or whatever in order to get back to the node.

Lucero
Thanks, all answers are helpful, in my case i don't need a path that uniquely identifies the individual node, I just need its simple path, so walking up the tree works okay. Wanted to make sure there wasn't something I was missing and my co-workers would laugh derisively at the extra couple lines.
Pride Fallon
+1  A: 

No there is no easy straightforward method or library function to do this for you. Bear in mind however that if the document is modified any previous path you calculate may be invalid. Also if an XML document allows an element or any of its ancestors to appear more than once with in a parent element you will need to track the specific index of that element.

Sounds like a useful little extension method though.

AnthonyWJones
+1  A: 

If you want to identify the document-unique path to the current node, the problem will be that, at each level up the tree, you'll have to know enough about all nodes at that level (either unique attribute [preferred] or index) to uniquely identify the node.

So for a given schema you might be able to build this, but there is no general-purpose method.

GalacticCowboy
++ This is exactly what I was going to say.
Greg