You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写正确的XPath 2.0表达式:判断是否存在18-22岁的Person

问题:编写XPath 2.0表达式判断是否存在符合年龄范围的Person

给定XML响应:

<People>
    <Person>
        <Age>29</Age>
    </Person>
    <Person>
        <Age>25</Age>
    </Person>
    <Person>
        <Age>18</Age>
    </Person>
    <Person>
        <Age>45</Age>
    </Person>
</People>

需求:编写XPath 2.0表达式,当存在至少一个年龄在18到22之间的Person时返回true。

当前使用的错误表达式:

boolean(//*:Person[xs:integer(substring(//*[local-name() = 'Age']/text(), 2)) >= 18 and 22 >= xs:integer(substring(//*[local-name() = 'Age']/text(), 2))])

触发错误:

A sequence of more than one item is not allowed as the first argument of substring() ("29", "25", ...)


解决方案

错误原因

你的表达式里,//*[local-name()='Age']/text()会选中所有Age元素的文本节点,返回一个包含多个字符串的序列,但substring函数只能接收单个字符串参数,因此报错。同时你错误地引用了全局的Age节点,而非当前Person节点下的Age,逻辑上也不符合需求。

正确表达式

基础写法

boolean(//*:Person[xs:integer(Age/text()) >= 18 and xs:integer(Age/text()) <= 22])

简洁写法(XPath 2.0支持)

boolean(//*:Person[xs:integer(Age) between 18 and 22])

说明

  1. 在Person节点的上下文内,直接用Age(或./Age)选中当前Person下的子元素Age,确保每个Person只检查自己的年龄。
  2. 无需使用substring,Age的文本本身是纯数字,直接转成整数即可。
  3. XPath 2.0的between语法可以简化范围判断逻辑,让表达式更易读。

内容的提问来源于stack exchange,提问作者xray1986

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 01:22:25