XPath中的非法参数异常

时间:2011-11-25 03:14:14

标签: java dom xpath illegalargumentexception

每当我运行下面的代码时,如果它找到了单词,它会给我一个Illegalargument异常,但是如果没有匹配,它将一直运行到没有错误结束。任何人都可以帮我找出解决方案吗?

public static void main(String[] args) throws MalformedURLException, SAXNotRecognizedException, SAXNotSupportedException, ParserConfigurationException, IOException, SAXException, XPathExpressionException {

   Parser p = new Parser();
   SAX2DOM sax2dom = null;
   org.w3c.dom.Node doc  = null;

   URL url = new URL("http://stackoverflow.com/users/1042952/mostafa");

   p.setFeature(Parser.namespacesFeature, false);
   p.setFeature(Parser.namespacePrefixesFeature, false);
   sax2dom = new SAX2DOM();
   p.setContentHandler(sax2dom);
   p.parse(new InputSource(new InputStreamReader(url.openStream())));
   doc = sax2dom.getDOM();

   final String term = "mostafa";
   String expression = "//*[contains(text(),$term)]";
   final QName termVariableName = new QName("term");
   class TermResolver implements XPathVariableResolver {
      @Override
      public Object resolveVariable(QName variableName) {
         return termVariableName.equals(variableName) ? term : null;
      }
   }
   javax.xml.xpath.XPath xpath = XPathFactory.newInstance().newXPath();
   xpath.setXPathVariableResolver(new TermResolver());
   Node node = (Node) xpath.evaluate(expression, p, termVariableName);
   System.out.println("her is it"+node);
}

1 个答案:

答案 0 :(得分:0)

1)您的即时错误是由于传递给evaluate的非法结果类型造成的。来自the docs

  

如果returnType不是XPathConstants中定义的类型之一(   NUMBER,STRING,BOOLEAN,NODE或NODESET)然后是   抛出IllegalArgumentException。

2)evaluate的第二个参数应该是一个上下文节点,而不是解析器。

使用类似的东西:

Node node = (Node) xpath.evaluate(expression, doc, XPathConstants.NODE);

注意:您可能打算将Mostafa大写。