Java 来自特定节点的Xpath查询

Java 来自特定节点的Xpath查询,java,xml,xpath,nodes,Java,Xml,Xpath,Nodes,我目前支持的常见查询来自根,意思是: public Object evaluate(String expression, QName returnType) {...} 现在我想从某个给定节点开始执行Xpath查询,例如: public Object evaluate(String expression, Node source, QName returnType) { ? } 然后,如果我通常的查询是这样的(这里有一个exmaple): //将文档加载到DOM文档中 DocumentBu

我目前支持的常见查询来自根,意思是:

public Object evaluate(String expression, QName returnType) {...}
现在我想从某个给定节点开始执行Xpath查询,例如:

public Object evaluate(String expression, Node source, QName returnType) { ? } 
然后,如果我通常的查询是这样的(这里有一个exmaple):

//将文档加载到DOM文档中
DocumentBuilderFactory domFactory=DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);//永远不要忘记这一点!
DocumentBuilder=domFactory.newDocumentBuilder();
documentdoc=builder.parse(“books.xml”);
//创建XPath工厂
XPathFactory=XPathFactory.newInstance();
//创建XPath对象
XPath=factory.newXPath();
//使XPath对象编译XPath表达式
XPathExpression expr=xpath.compile(“/inventory/book[3]/previous sibling::book[1]”);
//计算XPath表达式的值
Object result=expr.evaluate(doc,XPathConstants.NODESET);
节点列表节点=(节点列表)结果;
//打印输出
System.out.println(“第一选项:”);
对于(int i=0;i
对于上述方法(
public Object evaluate(字符串表达式、节点源、QName returnType);
),我需要进行什么样的更改才能实现这一点


谢谢!

一种简单的方法是将感兴趣的节点复制到一个新文档中,并将XPath应用到该新文档中。@beerbajay:事实上,我确实需要进入树中。回答如下:
//load the document into a DOM Document
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true); // never forget this!
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("books.xml");
//create an XPath factory
XPathFactory factory = XPathFactory.newInstance();
//create an XPath Object
XPath xpath = factory.newXPath();

//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);
NodeList 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("*******");