簡體   English   中英

評估Xpath時InputStream異常

[英]InputStream exception while evaluating Xpath

我得到: 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)

在嘗試使用InputStream對象評估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倍!

m.evaluate(q, null, XPathConstants.NODESET); 將null引用傳遞給評估方法,因此您創建了new DOMSource(null)我認為這對我而言似乎沒有意義,並且可能會在稍后導致相對於XPath inventory/book/chapter[3]/preceding-sibling::chapter//title被評估。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM