If I have a DOM, is it possible to get the reverse XPath of an element? For example, if I have :
<start>
<nodes>
<node>
<name>Whatever</name>
</node>
<node>
<name>Whatever 2</name>
</node>
</nodes>
</start>
If for example, I have a reference to the node with the name Whatever 2, is it possible to get back /start/nodes/node/name[. = "Whatever 2"]?
Here’s a very simple approach to walking up the tree using the Java DOM API in the Scala REPL:
First we import the relevant packages and set up our document builder and source:
Now to parse the example document:
This is a very simple function that recursively walks up the DOM to the document root:
And we pick the second
<name>node to test:We get what we expect:
It wouldn’t be hard to tweak the
pathfunction to avoid explicit recursion or to gather more information as it walks up the tree—for example indicating position when necessary to avoid ambiguity:Note that I’ve changed the type slightly to make it clear that this will only give us a valid XPath path for elements. We can test:
This is again what we expect.