是否有“if -then - else”在XPath中的声明? [英] Is there an "if -then - else " statement in XPath?
问题描述
似乎xpath中的所有丰富功能都可以执行if。但是,我的引擎一直坚持没有这样的功能,我几乎没有在网上找到任何文档(我发现了一些可疑的来源,但他们的语法不起作用)
It seems with all the rich amount of function in xpath that you could do an "if" . However , my engine keeps insisting "there is no such function" , and I hardly find any documentation on the web (I found some dubious sources , but the syntax they had didn't work)
我需要从字符串末尾删除':'(如果存在),所以我想这样做:
I need to remove ':' from the end of a string (if exist), so I wanted to do this:
if (fn:ends-with(//div [@id='head']/text(),': '))
then (fn:substring-before(//div [@id='head']/text(),': ') )
else (//div [@id='head']/text())
有什么建议吗?
推荐答案
是的,有一种方法可以在XPath 1.0中实现:
Yes, there is a way to do it in XPath 1.0:
concat(
substring($s1, 1, number($condition) * string-length($s1)),
substring($s2, 1, number(not($condition)) * string-length($s2))
)
这取决于两个串联互斥字符串,如果条件为假,则第一个为空( 0 * string-length(...)
),如果条件为真,则第二个为空。这被称为Becker的方法,归功于 Oliver Becker 。
This relies on the concatenation of two mutually exclusive strings, the first one being empty if the condition is false (0 * string-length(...)
), the second one being empty if the condition is true. This is called "Becker's method", attributed to Oliver Becker.
在您的情况下:
concat(
substring(
substring-before(//div[@id='head']/text(), ': '),
1,
number(
ends-with(//div[@id='head']/text(), ': ')
)
* string-length(substring-before(//div [@id='head']/text(), ': '))
),
substring(
//div[@id='head']/text(),
1,
number(not(
ends-with(//div[@id='head']/text(), ': ')
))
* string-length(//div[@id='head']/text())
)
)
虽然我会尝试在之前摆脱所有//
。
Though I would try to get rid of all the "//"
before.
此外,有可能 // div [@ id ='head']
返回多个节点。
请注意这一点—使用 // div [@ id ='head'] [1]
更具防御性。
Also, there is the possibility that //div[@id='head']
returns more than one node.
Just be aware of that — using //div[@id='head'][1]
is more defensive.
这篇关于是否有“if -then - else”在XPath中的声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!