我有以下两个代码段,它们做同样的事情,除了一个正在编译表达式,一个只是评估它。
//1st option - compile and run
//make the XPath object compile the XPath expression
XPathExpression expr = xpath.compile("/inventory/book[3]/preceding-sibling::book[1]");
//evaluate the XPath expression
Object result = expr.evaluate(doc, XPathConstants.NODESET);
nodes = (NodeList) result;
//print the output
System.out.println("1st option:");
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println("i: " + i);
System.out.println("*******");
System.out.println(nodeToString(nodes.item(i)));
System.out.println("*******");
}
//2nd option - evaluate an XPath expression without compiling
Object result2 = xpath.evaluate("/inventory/book[3]/preceding-sibling::book[1]",doc,XPathConstants.NODESET);
System.out.println("2nd option:");
nodes = (NodeList) result2;
//print the output
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println("i: " + i);
System.out.println("*******");
System.out.println(nodeToString(nodes.item(i)));
System.out.println("*******");
}
输出完全相同。编译和仅评估有什么区别?为什么要编译/不编译表达式?