无法在XPath中评估表达式 [英] Unable to evaluate expression in XPath

查看:353
本文介绍了无法在XPath中评估表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用XPath解析URL返回的XML文档,当我使用给定输入运行代码时,它可以工作,但是当将其输入作为用户输入时,则会引发异常。
代码:

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

例外情况:

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

类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;
    }
}


推荐答案

尝试评估XPath表达式时, 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).

在您的代码中,您有

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

// happily continue

这是一个电话麻烦如果初始化期间发生异常,则应在此处停止,并且不应继续。如果您完全不知道如何处理该错误,请使用 catch(Exception e){throw new Error(e); }

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.

作为问题的读者,我什至都不知道,这会导致异常冒泡,并希望由默认异常处理程序处理,该异常处理程序会打印堆栈跟踪并退出。知道在哪里抛出异常。您应该提供此信息。请注意,您还可以使用 someException.printStackTrace(); 获取将您指向正确行的堆栈跟踪。

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.

这篇关于无法在XPath中评估表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆