0
我得到: javax.xml.transform.TransformerException: Unable to evaluate expression using this context
InputStream的異常而計算XPath
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倍!
我試過用一個Node對象(不是NULL),它仍然產生相同的結果。 – ron