import java.util.Stack;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* Utility class for dealing with XML DOM elements.
*
*
* @author Mikkel Heisterberg, lekkim@lsdoc.org
*/
public class ElementUtil {
/**
* Constructs a XPath query to the supplied node.
*
* @param n
* @return
*/
public static String getXPath(Node n) {
if (null == n) return null;
Node parent = null;
Stack hierarchy = new Stack();
StringBuffer buffer = new StringBuffer();
hierarchy.push(n);
parent = n.getParentNode();
while (null != parent && parent.getNodeType() != Node.DOCUMENT_NODE) {
hierarchy.push(parent);
parent = parent.getParentNode();
}
Object obj = null;
while (!hierarchy.isEmpty() && null != (obj = hierarchy.pop())) {
Node node = (Node) obj;
boolean handled = false;
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element e = (Element) node;
if (buffer.length() == 0) {
buffer.append(node.getLocalName());
} else {
buffer.append("/");
buffer.append(node.getLocalName());
if (node.hasAttributes()) {
if (e.hasAttribute("id")) {
buffer.append("[@id='" + e.getAttribute("id") + "']");
handled = true;
} else if (e.hasAttribute("name")) {
buffer.append("[@name='" + e.getAttribute("name") + "']");
handled = true;
}
}
if (!handled) {
int prev_siblings = 1;
Node prev_sibling = node.getPreviousSibling();
while (null != prev_sibling) {
if (prev_sibling.getNodeType() == node.getNodeType()) {
if (prev_sibling.getLocalName().equalsIgnoreCase(node.getLocalName())) {
prev_siblings++;
}
}
prev_sibling = prev_sibling.getPreviousSibling();
}
buffer.append("[" + prev_siblings + "]");
}
}
}
}
return buffer.toString();
}
}
Kommentare (1)
13. Aug
Anonym sagt:
The code works fine, but I must change the Method node.getLocalName() in node.ge...The code works fine, but I must change the Method node.getLocalName() in node.getNodeName() thx!
Kommentar hinzufügen