在 XML 中多次解析單個 XPath 表示式

在這種情況下,你希望在評估之前編譯表示式,以便每次呼叫 evaluate 都不會同時表達相同的表示式。簡單的語法是:

XPath xPath = XPathFactory.newInstance().newXPath(); //Make new XPath
XPathExpression exp = xPath.compile("/documentation/tags/tag[@name='Java']//example");
DocumentBuilder builder = DocumentBuilderFactory.newInstance();
Document doc = builder.parse(new File("path/to/xml.xml")); //Specify XML file path

NodeList javaExampleNodes = (NodeList) exp.evaluate(doc, XPathConstants.NODESET); //Evaluate the XPath from the already-compiled expression

NodeList javaExampleNodes2 = (NodeList) exp.evaluate(doc, XPathConstants.NODESET); //Do it again

總的來說,對 XPathExpression.evaluate() 的兩次呼叫將比兩次呼叫 XPath.evaluate() 更有效。