是否有“if -then - else"?XPath 中的语句? [英] Is there an "if -then - else " statement in XPath?
问题描述
似乎有了 xpath 中所有丰富的功能,您就可以执行 "if" .然而,我的引擎一直坚持没有这样的功能",我在网上几乎找不到任何文档(我发现了一些可疑的来源,但它们的语法不起作用)
我需要从字符串的末尾删除 ':'(如果存在),所以我想这样做:
if (fn:ends-with(//div [@id='head']/text(),': '))然后 (fn:substring-before(//div [@id='head']/text(),': ') )else (//div [@id='head']/text())
有什么建议吗?
是的,在 XPath 1.0 中有一种方法可以做到:
<前>连接(substring($s1, 1, number($condition) * string-length($s1)),substring($s2, 1, number(not($condition)) * string-length($s2)))这依赖于两个互斥字符串的连接,如果条件为假,第一个为空 (0 * string-length(...)
),第二个为空,如果条件为真.这称为贝克尔方法",归因于 Oliver Becker (原始链接现已失效,网络存档有一个副本).
就你而言:
<前>连接(子串(substring-before(//div[@id='head']/text(), ': '),1、数字(结尾(//div[@id='head']/text(),':'))* string-length(substring-before(//div [@id='head']/text(), ':'))),子串(//div[@id='head']/text(),1、数字(不是(结尾(//div[@id='head']/text(),':')))* 字符串长度(//div[@id='head']/text())))虽然我会尝试去掉之前所有的 "//"
.
此外,//div[@id='head']
有可能返回多个节点.
请注意这一点 - 使用 //div[@id='head'][1]
更具防御性.
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())
Any advice?
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)) )
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 (original link is now dead, the web archive has a copy).
In your case:
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.
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屋!