0

我得到: javax.xml.transform.TransformerException: Unable to evaluate expression using this context

    at com.sun.org.apache.xpath.internal.XPath.execute(Unknown Source)
    at com.sun.org.apache.xpath.internal.jaxp.XPathImpl.eval(Unknown Source)
    at com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(Unknown Source)
    at XPathImplementation.evaluate(XPathImplementation.java:136)
    at Main.main(Main.java:23)
Caused by: java.lang.RuntimeException: Unable to evaluate expression using this context
    at com.sun.org.apache.xpath.internal.axes.NodeSequence.setRoot(Unknown Source)
    at com.sun.org.apache.xpath.internal.axes.LocPathIterator.execute(Unknown Source)

在尝试使用InputStreamobject 评估 Xpath 表达式时,我尝试对其进行调试,但没有发现任何错误(当然我错过了一些东西..)。这是代码:

从主要:

    XPathProject m = new XPathImplementation();
    m.loadXML("books.xml"); 
    String q = "inventory/book/chapter[3]/preceding-sibling::chapter//title";
    Object ob = m.evaluate(q, null, XPathConstants.NODESET);

我们使用这种evaluate方法:

public Object evaluate(String expression, Node source, QName returnType) throws XPathExpressionException,IllegalArgumentException,NullPointerException, TransformerException
{
...
  InputStream  is = nodeToInputStream(source);
  Object returnedObject= xpath.evaluate(expression, is, returnType); // it happens here !!

... more code
}

辅助方法nodeToInputStream

/*
 *    Convert Node object into InputStream object
 */

    private InputStream nodeToInputStream(Node node) throws TransformerException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        StreamResult outputTarget = new StreamResult(outputStream);
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        t.transform(new DOMSource(node), outputTarget);
        return new ByteArrayInputStream(outputStream.toByteArray());
}

知道我哪里出错了吗?10倍!

4

1 回答 1

1

好吧m.evaluate(q, null, XPathConstants.NODESET);,传入对评估方法的空引用,因此您创建new DOMSource(null)我认为这对我来说似乎没有意义,并且可能会导致稍后在inventory/book/chapter[3]/preceding-sibling::chapter//title评估相对 XPath 时出现该错误。

于 2012-05-13T13:39:00.480 回答