XPath 1.0中如何在指定范围内统计唯一值?
XPath 1.0 统计configuration_B内type_a/input_1唯一值数量的解决方案
我在使用XML与XPath 1.0,基于libxml2的Schematron模块(该模块的断言测试依赖XPath模块),现在简化为XPath表达式问题:
给定如下XML代码:
<configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <configuration_A> <slot_1> <type_a> <input_1>TEXT_1</input_1> </type_a> </slot_1> </configuration_A> <configuration_B> <slot_1> <type_a> <input_1>TEXT_1</input_1> </type_a> </slot_1> <slot_2> <type_a> <input_1>TEXT_2</input_1> </type_a> </slot_2> <slot_3> <type_a> <input_1>TEXT_2</input_1> </type_a> </slot_3> <slot_4> <type_a> <input_1>TEXT_3</input_1> </type_a> </slot_4> <slot_5> <type_b> <input_1>TEXT_3</input_1> </type_b> </slot_5> </configuration_B> </configuration>
我的需求是统计configuration_B范围内type_a/input_1的唯一值数量,这个需求在XPath 2.0中可以通过以下表达式实现:
count(distinct-values(//configuration_B//type_a/input_1/text()))
我参考相关方案改写为XPath 1.0表达式:
//configuration_B//type_a/input_1[not(. = preceding::input_1)]
但这个表达式存在问题:preceding轴会包含configuration_A下的input_1,导致结果缺失/configuration_B/slot_1/type_a/input_1,且错误处理了/configuration_B/slot_2/type_a/input_1。我尝试许久后怀疑XPath 1.0无法实现,特寻求解决方案,测试基于libxml2的XPath示例程序。
更新:解决方案
已采纳Heiko Theißen的正确答案,该方案可实现与XPath 2.0 distinct-values(//configuration_B//type_a/input_1/text())完全一致的输出。
同时我也找到了适配自身需求的方案:
- 若要识别重复项以触发断言,可使用以下表达式,统计结果数量,若不为0则触发断言:
//configuration_B//type_a/input_1[(. = preceding::type_a/input_1[../../parent::configuration_B])]
- 若要显示所有重复实例,可添加
following轴的判断:
//configuration_B//type_a/input_1[((. = following::type_a/input_1[../../parent::configuration_B]) or (. = preceding::type_a/input_1[../../parent::configuration_B])) ]
内容的提问来源于stack exchange,提问作者JoseleMG
相关产品推荐
相关产品推荐

