每当我运行下面的代码时,如果它找到这个单词,它就会给我一个非法异常,但如果没有匹配,它将一直持续到结束,没有错误。有人可以帮我找到解决方案吗?
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) 您的直接错误是由于传递给 evaluate
的结果类型非法所致。来自 the docs :
If returnType is not one of the types defined in XPathConstants ( NUMBER, STRING, BOOLEAN, NODE or NODESET) then an IllegalArgumentException is thrown.
2) evaluate
的第二个参数应该是上下文节点,而不是解析器。
使用这样的东西:
Node node = (Node) xpath.evaluate(expression, doc, XPathConstants.NODE);
注意:您可能想将 Mostafa
大写。
关于java - XPath 中的非法参数异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8264498/