在 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()
更有效。