英文:
XPath that returns true when at least one element matches
问题
boolean(//*[local-name() = 'Person'][xs:integer(substring(./Age/text(), 1)) >= 18 and xs:integer(substring(./Age/text(), 1)) <= 22])
英文:
Let's assume we have the following XML response:
<People>
    <Person>
        <Age>29</Age>
    </Person>
    <Person>
        <Age>25</Age>
    </Person>
    <Person>
        <Age>18</Age>
    </Person>
    <Person>
        <Age>45</Age>
    </Person>
</People>
I want an xpath 2.0 expression that will return true if there is at least one person with age between 18 and 22.
My current expression is:
boolean(//*:Person[xs:integer(substring(//*[local-name() = 'Age']/text(), 2)) >= 18 and 22 >= xs:integer(substring(//*[local-name() = 'Age']/text(), 2))])
But this expression is not recursive so it produces the following error:
>A sequence of more than one item is not allowed as the first argument of substring() ("29", "25", ...)
Any idea as to how I can achieve what I need?
答案1
得分: 3
在XPath 2.0中,这是 exists(//Person[Age = (18 to 22)])。
英文:
In XPath 2.0 this is exists(//Person[Age = (18 to 22)])
答案2
得分: 1
这个XPath,
boolean(/People/Person[Age > 18][Age < 22])
将会返回true,当且仅当至少有一个Person的年龄在18到22之间,不包括边界值。
注意:
- 如果这个XPath嵌入在XML/XSLT中,请确保使用
&lt;代替<。 - 如果要包含边界值,请使用
>=和/或<=。 - 除非您试图消除命名空间,否则没有理由使用
local-name()和*:,在这里命名空间不起作用,而且应该被接受而不是被消除。 
英文:
This XPath,
boolean(/People/Person[Age > 18][Age < 22])
will return true iff at least one Person has an age between 18 and 22, exclusive.
Notes:
- 
Be sure to use
&lt;for<if this XPath is embedded in XML/XSLT. - 
Use
>=and/or<=for inclusive endpoints. - 
There is no reason to use
local-name()and*:unless you are trying to defeat namespaces, which- are not in play here anyway, but
 - can and should be accommodated, not defeated.
 
 
答案3
得分: 0
这里有一个有点复杂的代码,它使用了 count 和 translate:
count(//Age[translate(translate(., "1", "X"), "89", "YY") = "XY" or .= "22" or translate(translate(., "2", "X"), "01", "YY") = "XY"]) > 0
22 是一个特殊情况,因为 translate 将其转换为 XX。
英文:
here's a twisted one that uses count and translate
count(//Age[translate(translate(., "1", "X"),"89","YY") = "XY" or .="22" or translate(translate(., "2", "X"),"01","YY") = "XY"]) > 0
22 is an special case since translate turns it into XX
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论