Java 17中XPath无/foo匹配时返回null或空字符串的解决方法
解决方案:实现无匹配时返回null或空字符串
一、实现无匹配时返回null(结合Java代码)
纯XPath表达式在JAXP指定XPathConstants.STRING返回类型时,空序列会被自动转为空字符串而非null,所以需要结合Java代码做判断:
- 先准备判断
/foo节点是否存在的XPath表达式:
exists(/foo)
- 在Java代码中先执行这个判断,再决定返回结果:
// 初始化判断表达式 XPathExpression hasFooExpr = xpath.compile("exists(/foo)"); Boolean hasFoo = (Boolean) hasFooExpr.evaluate(context, XPathConstants.BOOLEAN); if (hasFoo) { // 执行拼接逻辑,可选追加换行 XPathExpression joinExpr = xpath.compile("concat(string-join(/foo/bar, codepoints-to-string(10)), codepoints-to-string(10))"); return (String) joinExpr.evaluate(context, XPathConstants.STRING); } else { return null; }
二、纯XPath表达式实现:无匹配时返回空字符串
如果不需要返回null,仅要求无匹配时返回空字符串、仅匹配成功时追加换行,直接用XPath 3.0的条件表达式即可:
if (exists(/foo)) then concat(string-join(/foo/bar, codepoints-to-string(10)), codepoints-to-string(10)) else ''
要是不需要追加换行,只返回拼接后的内容(无匹配时为空串),用这个表达式:
if (exists(/foo)) then string-join(/foo/bar, codepoints-to-string(10)) else ''
原理
exists(/foo)会检查根节点下是否存在/foo节点,存在则执行拼接逻辑(可选加换行),不存在直接返回空字符串,解决了原表达式无匹配时返回换行符的问题。
内容的提问来源于stack exchange,提问作者Garret Wilson
相关产品推荐
相关产品推荐

