나는 식을 컴파일하고 하나만 평가하는 것 외에는 같은 것을하는 다음 두 코드 세그먼트를 가진다.XPath 표현식을 컴파일해야하는 이유는 무엇입니까?
//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("*******");
}
출력은 완전히 동일합니다. 컴파일과 평가의 차이점은 무엇입니까? 표현식을 컴파일하거나 컴파일하지 않는 이유는 무엇입니까?
동일한 xpath를 반복해서 사용하는 경우 컴파일하여 시간을 절약하십시오. 당신이 갈 때마다 다른 xpath를 사용한다면 (예를 들어, 당신이 그것을 즉석에서 생성 할 때), 컴파일 할 필요가 없습니다. – shakurov