Find the unambiguous XPath for an arbitrary Element
A problem I often come across (but can't find any reference to anyone else having in searches) is needing to extract an unambiguous XPath for an element.
Generally it'll be because a function is expected to output something which needs to include a reference back to the element within an XML structure where the function was only given a DOM Element.
So here's a Javascript implementation of a function that, given a Node Element, returns an unambiguous XPath for it...
function findXPath(node, suffix) {
if (node) {
if (node.nodeType == 1) {
var siblings = node.selectNodes('preceding-sibling::' + node.nodeName).length;
return findXPath(node.parentNode, node.nodeName + ((siblings) ? '[' + (siblings + 1) + ']' : '') + ((suffix) ? '/' + suffix : ''));
}
return findXPath(node.parentNode, suffix);
}
return '/' + suffix;
}
var XPath = findXPath(element);
It isn't hard to make it work for Node Attributes either (as long as support for node.ownerElement is present) or Text Nodes. But I have yet to find a need for that functionality.