Unable to evaluate expression in XPath

I;m using XPath to parse XML document returned by a URL, when i run my code with given inputs it works but when giving it inputs as a user input it throws an exception. The Code:

    class{
        private String generalQuery =  "//@*";
    method(){
        System.out.println("Enter URL");
        url = scan.nextLine();
        URL oracle = new URL(url);
        InputStream is = oracle.openStream();

        org.w3c.dom.Document doc = null;
        DocumentBuilderFactory domFactory;
        DocumentBuilder builder;

        try {
            domFactory = DocumentBuilderFactory.newInstance();
            domFactory.setNamespaceAware(true);
            builder = domFactory.newDocumentBuilder();
            doc = builder.parse(is);
        } catch (Exception ex) {
            System.err.println("unable to load XML: " + ex);
        }

    Map <String, String> params = new HashMap<String, String> ();

            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();
            xpath.setNamespaceContext(new NameSpaces(doc));
            XPathExpression expr = xpath.compile(generalQuery);
            Object result = expr.evaluate(doc, XPathConstants.NODESET); // exception thrown here

            NodeList nl = (NodeList) result;

            for (int i = 0 ; i < nl.getLength() ; i++){
                Node n = (Node)nl.item(i);
                params.put(n.getNodeName(), n.getNodeValue());
            }

            return params;
}
}

The Exception:

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

The class NameSpaces :

import java.util.Iterator;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import org.w3c.dom.Document;

public class NameSpaces implements NamespaceContext {
    private Document sourceDocument;

    public NameSpaces(Document document) {
        sourceDocument = document;
    }

    @Override
    public String getNamespaceURI(String prefix) {
        if (prefix.equals(XMLConstants.DEFAULT_NS_PREFIX)) {
            return sourceDocument.lookupNamespaceURI(null);
        } else {
            return sourceDocument.lookupNamespaceURI(prefix);
        }
    }

    @Override
    public String getPrefix(String namespaceURI) {
        return sourceDocument.lookupPrefix(namespaceURI);
    }

    @Override
    public Iterator<String> getPrefixes(String namespaceURI) {
        return null;
    }
}

The exception "Unable to evaluate expression using this context" may also result from a null document when trying to evaluate an XPath expression. (I had the same error and it took me a while to figure out I did not initialize my document properly).

In your code you have

try {
  // load document
}
catch (Exception ex) {
  System.err.println("unable to load XML: " + ex);
}

// happily continue

This is a call for trouble. If an exception happens during initialization you should STOP right there and you should not continue. If you have absolutely no idea how to handle the error, use catch(Exception e) { throw new Error(e); }. This will cause exceptions to bubble up and hopefully be handled by the default exception handler which prints a stack trace and exits.

As the reader of your question I don't even know where the exception was thrown. You should provide this information. Note that you can also use someException.printStackTrace(); to get the stack trace which points you to the correct line.

[TISTUD-8573] Error reporting:Unable to evaluate expression using , TransformerException: Unable to evaluate expression using this context. at com.​sun.org.apache.xpath.internal.XPath.execute(XPath.java:367). Can I make the value in an XPath query another XPath expression somehow? (Hoping this is possible) Here's a simplified version of what I'm trying to do: Let's say I have an XML structure like this:

What you seem to be missing is a NameSpaceContext that you can implement yourself.

Also see this thread: NamespaceContext and using namespaces with XPath

Example:

class NamespaceResolver implements NamespaceContext {

    private final Document document;

    public NamespaceResolver(Document document) {
        this.document = document;
    }

    public String getNamespaceURI(String prefix) {
        if (prefix.equals(XMLConstants.DEFAULT_NS_PREFIX)) {
            return document.lookupNamespaceURI(null);
        } else {
            return document.lookupNamespaceURI(prefix);
        }
    }

    public String getPrefix(String namespaceURI) {
        return document.lookupPrefix(namespaceURI);
    }

    @SuppressWarnings("rawtypes")
    public Iterator getPrefixes(String namespaceURI) {
        // not implemented
        return null;
    }

}

Then you initiate the XPath instance like this:

    getXPath().setNamespaceContext(new NamespaceResolver(doc));

Re: How do I debug "Unable to evaluate expression using this , Null handling in XPath and XPathExpression is inconsistent. TransformerException: Unable to evaluate expression using this context, that is  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 ..) .

In my case this was not due to a null document, but due to an empty document with no root element. Appending the latter solved the issue.

[JDK-8066039] XPath: inconsistent definition for evaluate methods , p> <p>See "Evaluation of XPath Expressions" section of JAXP 1.3 spec for toString()); } catch ( XPathExpressionException e) { Assert.fail("Fail during test  An XPath expression is not thread-safe. It is the application’s responsibility to make sure that one XPathExpression object is not used from more than one thread at any given time, and while the evaluate method is invoked, applications may not recursively call the evaluate method.

Unable to evaluate expression using this context_Java_chenzubang , newXPath(); return (String) xPath.evaluate("/project/version", document, NODESET); } catch (XPathExpressionException e) { reportError((Element) +</​array>$")) { fail(); } for (String element : elements) { if (!xml.contains(element)) { fail​(); } } }. The Evaluate XPath Expression dialog box opens. To toggle the evaluation mode, click the Advanced / Simple button. In either mode, the dialog box features a history of the recently evaluated expressions, completion, syntax-checking and highlighting, as well as some semantic error checking of the entered expression.

Java Code Examples of javax.xml.xpath.XPathExpressionException, Hello, I have installed NextCloud on a shared server and it went without a hitch. I was able to log in, configure my account and added files. XML Xpath not working If I then go to "Evaluate XPath expression" and paste in that exact same XPath, it says "Error: unable to evaluate xpath expression" and the

Java Code Examples javax.xml.xpath.XPathExpressionException, Failed to evaluate xpath expression ora:formatDate. Problem: Using the Oracle XPath extension function ora:formatDate in your transformation  In Robins's answer ends-with is not supported in xpath 1.0 too.. Only starts-with is supported So if your condition is not very specific..You can Use like this which worked for me

Comments
  • What is the type of doc in this code snippet?
  • it's XML document created by dom
  • What is NameSpaces? The setNamespaceContext method expects an argument of type NamespaceContext. As @Ian pointed out, you also didn't tell us the type of doc. As written, your question won't even compile and you've left us to guess at things you should have included.
  • i edited the question with all information you may need
  • Yep in my case the error was due to a null document. This was the result of an upstream bug. Thanks.
  • This is probably right, but the OP didn't really include enough information to know for sure.
  • i had already made that, the something is the name of the class NameSpaceResolver is just NameSpaces in my code
  • @Brass Block: Maybe you also could show us the XML. Does the xml have proper namespace declarations?