Xpath - evaluate函数返回javax.xml.transform.TransformerException

时间:2016-03-31 22:34:53

标签: java xml xpath

这是我第一次使用XPath,而我正在尝试查询一个非常基本的示例。

    String xml = "<resp><status>good</status><msg>hi</msg></resp>";

    XPathFactory xpathFactory = XPathFactory.newInstance();
    javax.xml.xpath.XPath xpath = xpathFactory.newXPath();

    InputSource source = new InputSource(new StringReader(xml));

    String status = "";
    try {
        status = (String) xpath.evaluate("//resp/status", source,XPathConstants.STRING);
    } catch (Exception e) {
        e.printStackTrace();
    }

    System.out.println("status=" + status);

我收到以下例外:

  

javax.xml.transform.TransformerException:无法使用此上下文计算表达式   com.sun.org.apache.xpath.internal.XPath.execute(未知来源)at   com.sun.org.apache.xpath.internal.jaxp.XPathImpl.eval(未知来源)     在com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(未知   来源)Heandlers.HTTP.x(HTTP.java:74)at   Views.Main.main(Main.java:15)引起:java.lang.RuntimeException:   无法使用此上下文评估表达式   com.sun.org.apache.xpath.internal.axes.NodeSequence.setRoot(未知   来源)at   com.sun.org.apache.xpath.internal.axes.LocPathIterator.execute(未知   来源)......还有5个   --------- java.lang.RuntimeException:无法使用此上下文计算表达式   com.sun.org.apache.xpath.internal.axes.NodeSequence.setRoot(未知   来源)at   com.sun.org.apache.xpath.internal.axes.LocPathIterator.execute(未知   来源)com.sun.org.apache.xpath.internal.XPath.execute(未知   来源)at   com.sun.org.apache.xpath.internal.jaxp.XPathImpl.eval(未知来源)     在com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(未知   来源)Heandlers.HTTP.x(HTTP.java:74)at   Views.Main.main(Main.java:15)   ---------------链接到------------------ javax.xml.xpath.XPathExpressionException:   javax.xml.transform.TransformerException:无法评估   表达式使用此上下文   com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(未知   来源)Heandlers.HTTP.x(HTTP.java:74)at   Views.Main.main(Main.java:15)引起:   javax.xml.transform.TransformerException:无法评估   表达式使用此上下文   com.sun.org.apache.xpath.internal.XPath.execute(未知来源)at   com.sun.org.apache.xpath.internal.jaxp.XPathImpl.eval(未知来源)     ... 3更多引起:java.lang.RuntimeException:无法评估   表达式使用此上下文   com.sun.org.apache.xpath.internal.axes.NodeSequence.setRoot(未知   来源)at   com.sun.org.apache.xpath.internal.axes.LocPathIterator.execute(未知   来源)... 5 more status =

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

听起来您使用的是无效的InputSource,例如org.w3c.css.sac.InputSource。确保您已导入org.xml.sax.InputSource