从JavaDoc:返回:作为评估表达式并将结果转换为字符串的结果的字符串。
/**
* ...
* ...
* @return The <code>String</code> that is the result of evaluating the expression and converting the result to a
* <code>String</code>.
* ...
* ...
*/
String javax.xml.xpath.XPathExpression.evaluate(Object item)
问题是,如果表达式什么也没找到,那么这里的合同有点多了。在所有实现中,null是否为有效/无效返回?返回API在哪里定义?在JSR?
答案 0 :(得分:3)
如果我没记错的话,XPath中没有null。我的猜测是返回空字符串。
更新:快速了解XPath 2.0和XPath 2.0 Functions规格确认了这种感觉。
答案 1 :(得分:1)
这可能不是预期的答案。
<types>
<type id="1">
<href>aaa</href>
</type>
</types>
假设你写了一个方法,@id
找到href
。
Double findIdByHref(final String href) {
evaluate("/:types/:type[:href='bbb']/@id", NUMBER);
}
此方法为0
返回null
而不是bbb
作为href
final Double id = findByHref("bbb"); // not null
我必须像这样修改
Double findIdByHref(final String href) {
final Node node = evaluate("/:types/:type[:href='bbb']", NODE);
if (node == null) {
return null;
}
return evaluate("@id", node);
}