0

I get : 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)

While trying to evaluate an Xpath expression using InputStream object , I've tried to debug it however found nothing wrong (and of course I missed something ..) . Here's the code:

From Main:

    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);

We use this evaluate method :

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
}

Auxiliary method 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());
}

Any idea where did I go wrong ? 10x!

1 Answer 1

1

Well m.evaluate(q, null, XPathConstants.NODESET); passes in a null reference to the evaluate method so you create new DOMSource(null) I think which does not seem to make sense to me and probably results in that error later where a relative XPath inventory/book/chapter[3]/preceding-sibling::chapter//title is evaluated.

Sign up to request clarification or add additional context in comments.

1 Comment

I've tried with a Node object (that is not a NULL) and it still produces the same result .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.