This returns the complete XPath expression for this
node.
// Handle elements
if (node.getNode() instanceof Element) {
JDOMNode parent = node.getParentNode();
// If this is null, we're at the root
if (parent == null) {
return "/" + node.getQName();
}
// Otherwise, build a path back to the root
Stack stack = new Stack();
stack.add(node);
do {
stack.add(parent);
parent = parent.getParentNode();
} while (parent != null);
// Build the path
StringBuffer xpath = new StringBuffer();
while (!stack.isEmpty()) {
xpath.append(getElementXPath((JDOMNode)stack.pop()));
}
return xpath.toString();
}
// Handle attributes
if (node.getNode() instanceof Attribute) {
Attribute attribute = (Attribute)node.getNode();
JDOMNode parent = node.getParentNode();
StringBuffer xpath = new StringBuffer("//")
.append(parent.getQName())
.append("[@")
.append(node.getQName())
.append("='")
.append(attribute.getValue())
.append("']");
return xpath.toString();
}
// Handle text
if (node.getNode() instanceof String) {
StringBuffer xpath = new StringBuffer(
new XPathDisplayNode(node.getParentNode()).getXPath())
.append("[child::text()]");
return xpath.toString();
}
// Other node types could follow here
return "Node type not supported yet.";