I would be possible to generate xpath statements from the DOM simply by walking back up the nodes from a given node, though to do this generically enough, taking into account attribute values on each node, would make the resulting code next to useless. For example (which comes with a warning that this will find the first node that has a given name, xpath is much more that this and you may as well just use the xpath //foo2):import java.io.ByteArrayInputStream;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;public class XPathExample{ private static String getXPath(Node root, String elementName) { for (int i = 0; i < root.getChildNodes().getLength(); i++) { Node node = root.getChildNodes().item(i); if (node instanceof Element) { if (node.getNodeName().equals(elementName)) { return "/" + node.getNodeName(); } else if (node.getChildNodes().getLength() > 0) { String xpath = getXPath(node, elementName); if (xpath != null) { return "/" + node.getNodeName() + xpath; } } } } return null; } private static String getXPath(Document document, String elementName) { return document.getDocumentElement().getNodeName() + getXPath(document.getDocumentElement(), elementName); } public static void main(String[] args) { try { Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( new ByteArrayInputStream( ("<foo><foo1>Foo Test 1</foo1><foo2><another1><test1>Foo Test 2</test1></another1></foo2><foo3>Foo Test 3</foo3><foo4>Foo Test 4</foo4></foo>").getBytes() ) ); String xpath = "/" + getXPath(document, "test1"); System.out.println(xpath); Node node1 = (Node)XPathFactory.newInstance().newXPath().compile(xpath).evaluate(document, XPathConstants.NODE); Node node2 = (Node)XPathFactory.newInstance().newXPath().compile("//test1").evaluate(document, XPathConstants.NODE); //This evaluates to true, hence you may as well just use the xpath //test1. System.out.println(node1.equals(node2)); } catch (Exception e) { e.printStackTrace(); } }}同样,您可以编写一个 XML 转换,将一个 xml 文档转换为一系列 xpath 语句,但这种转换会比首先编写 xpath 更复杂,因此在很大程度上毫无意义.Likewise you could write an XML transformation that turned an xml document into a series of xpath statements but this transformation would be more complicated that writing the xpath in the first place and so largely pointless. 这篇关于获取 XML 标签的 XPath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-01 14:24