我需要在 XML 文档中找到文本元素的确切 XPath。我认为这样做的一种方法是将 Document 转换为字符串,在子字符串周围添加一个临时标记,将其转换回 Document,然后找到 XPath。
这是我到目前为止所拥有的:
public String findXPathInXMLString(int startIndex, int endIndex, String string) throws IOException, ParserConfigurationException, SAXException {
Conversion conversion = new Conversion();
String xpath;
//Step 1. Replace start to end index with temporary tag in string document
StringBuilder stringBuilder = new StringBuilder(string);
stringBuilder.replace(startIndex, endIndex, "<findXPathInXMLStringTemporaryTag>" + string.substring(startIndex, endIndex) + "</findXPathInXMLStringTemporaryTag>");
//Step 2. Convert string document to DOM document & Find XPath of temporary tag in DOM document
xpath = "/" + getXPath(conversion.stringToDocument(stringBuilder.toString()), "findXPathInXMLStringTemporaryTag");
//Step 3. Cut off last part of the XPath
//xpath = xpath.substring(0, 2).replace("/documentXPathTemporaryTag", "");
//Step 4. Return the XPath
return xpath;
}
public String getXPath(Document root, String elementName) {
try {
XPathExpression expr = XPathFactory.newInstance().newXPath().compile("//" + elementName);
Node node = (Node) expr.evaluate(root, XPathConstants.NODE);
if (node != null) {
return getXPath(node);
}
} catch (XPathExpressionException e) {
}
return null;
}
public String getXPath(Node node) {
if (node == null || node.getNodeType() != Node.ELEMENT_NODE) {
return "";
}
return getXPath(node.getParentNode()) + "/" + node.getNodeName();
}
到目前为止,我遇到的问题是该方法getXPath
没有放置,[x]
因此返回的 XPath 是错误的,因为子字符串可能位于[3]
特定标记的 rd 实例中,在这种情况下,XPath 将应用于所有具有相同路径的节点。我想得到一个只能引用一个特定元素的确切路径。