Schmacker

I'm currently doing some work with C# and XML, and am looking for some particular functionality. I want to be able to know the path (as in /a[1]/b[1]/c[2]/text()[4]) of the node that I'm currently at. I want to do something like the following:
Code Snippet


//open the XML document up and store it in memory
//get a list of all the nodes that exist in the document
//got through the list looking for some particular text or other such indicator
//when I find that indicator, find out what the path is to my current node


I am currently opening the file up with the XmlDocument class and selecting nodes and such with the XPathNavigator functionality.

My question is, does the built in classes have a way for me to get the path out of them And if they do, how do I do it

Any pointers or suggestions are appreciated

Thanks


Re: XML and the .NET Framework (C#) Getting the Path of an XML Node

AndreyShchekin

As far as I know there is no direct solution.

You can traverse the element ancestors with SelectAncestors function, then ask each ancestor for it's name, type and position.

Position (xpath function) will require context, but you can probably get it from the ancestor's direct parent.





Re: XML and the .NET Framework (C#) Getting the Path of an XML Node

Phil Fearon

I started trying a response describing building arrays of hashtables and managing a level counter when iterating through nodes using XmlReader. The hashtable is then ulitmately used to build a tree of objects much like a tree-view.

So, just by calclulating a single absolute position of an element node within a document (using the 'ancestor' axis) you can step backwards through each parent object, building the path (backwards) as you go - the same as in a visual tree-view control

However, this is hard to implement and even harder to describe so hopefully someone else has some ideas.

A number of good visual XSL/XPath tools like Oxygen and Stylus Studio (XML-Spy may also do this now) out there generate XPath locations on the fly as you describe, and I'm publishing one at the end of this month too (more light-weight though) - so it would be good to learn if there were an easier method than the one I used.

pgf






Re: XML and the .NET Framework (C#) Getting the Path of an XML Node

Dimitre_Novatchev - MSFT

Do have a look at my XSLT solution -- then implement it in C#:

http://www.topxml.com/code/default.asp p=3&id=v20010323001030

Cheers,

Dimitre Novatchev