This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes XML and Related Technologies and the fly likes Find XPath Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Engineering » XML and Related Technologies
Bookmark "Find XPath" Watch "Find XPath" New topic
Author

Find XPath

chack boom
Greenhorn

Joined: Mar 30, 2005
Posts: 2
If I know a xml Element, how can I programaticly find xPath for this Element? Is there any free or not free software to do this? I am not looking for GUI tool. I mean PROGRAMATICALLY find xpath. Thanks
Dave Lenton
Ranch Hand

Joined: Jan 20, 2005
Posts: 1241
The problem is that a given node may have several different XPaths to get to it. For example, take the following XML:


The node containing "bob" could be reached by several different XPaths:


and so on.

There may be tools out there to provide XPaths for a particular node, but it may just be simpler to write your own method - that way you can get the exact XPath that you want. Besides, this seems like a bit of an odd way to go about things - normally XPaths are used to find a node, not the other way around!
[ March 31, 2005: Message edited by: Dave Lenton ]

There will be glitches in my transition from being a saloon bar sage to a world statesman. - Tony Banks
chack boom
Greenhorn

Joined: Mar 30, 2005
Posts: 2
I mean I know Element. I want to find xpath. For example, element.getXPath();
Dave Lenton
Ranch Hand

Joined: Jan 20, 2005
Posts: 1241
Even so, you'll still have a problem because there are usually more than one XPath for any given node or element. One option would be to write your own method for getting an XPath - you could have a method that takes an node or element and uses methods such as getParentNode() to work out the path back to the root. This may need some way of working out which child of the parent the current node/element is (e.g. first, second etc). Throw in a bit of recursion, and hey presto, a simple XPath. Alternatively this same kind of thing could be achieved using XSLT.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Find XPath
 
Similar Threads
Is there a way to compare 2 xpaths in JSTL?
parsing response from a webService in BPEL
Some puzzles about org.apache.soap.Envelope
want to remove node from dom
One big XML file or lots of small ones