如何编写XPath判断元素是否包含预定义列表中的全部属性?
解决方法
要判断元素是否包含预定义列表里的所有属性,你需要修改条件逻辑,从“存在任一属性”改为“所有属性都存在”,以下是两种可行的实现方式:
方式一:直接逐个检查属性存在性
这种方式适合属性数量不多的场景,逻辑直观清晰:
let $element := <country type="" class="" ref="" ana=""/> return if($element/@type and $element/@class and $element/@ref and $element/@ana) then 'All attributes are present' else 'You can add attributes'
只要其中任意一个属性不存在,条件就会返回false。
方式二:用every-satisfy批量检查
如果预定义的属性列表较长,用这种批量检查的方式更易维护:
let $element := <country type="" class="" ref="" ana=""/> let $required-attrs := ('type', 'class', 'ref', 'ana') return if(every $attr-name in $required-attrs satisfies $element/@*[local-name() = $attr-name]) then 'All attributes are present' else 'You can add attributes'
这里通过every...satisfies表达式,确保列表中的每一个属性名,都能在元素的属性中找到匹配项。
内容的提问来源于stack exchange,提问作者wsalesky
相关产品推荐
相关产品推荐

