如果在 XPath 1.0 中的 else [英] If then else in XPath 1.0

查看:24
本文介绍了如果在 XPath 1.0 中的 else的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下一个表达式:

population = tree.xpath('(//tr/td/b/a[contains(text(), "Population")]/../../following-sibling::td/span/following-sibling::text())[1] or'
                            '//tr/td/b/a[contains(text(), "Population")]/../../following-sibling::td/span/text())

返回真".

如果我使用|"代替 'or',它结合了第 1 条和第 2 条路径的值,例如 ['11 061 886', '▼'].

If I use "|" instead of 'or', it combines values of the 1st and 2nd paths, like this ['11 061 886', '▼'].

如何使逻辑像:

If the 1st path exists:
    get the 1st value
elif the 2nd path exists:
    get the 2nd value
else:
    pass

?

我明白这很简单,但找不到答案.

I understand that this is simple, but can't find the answer.

推荐答案

如果您真的找不到 XPath 2.0 处理器,XPath 1.0 中有一些可能适合您的解决方法.

If you really can't find an XPath 2.0 processor, there are some workarounds in XPath 1.0 which may work for you.

如果要选择节点集,则代替

If you want to select node-sets, then in place of

if (A) then B else C

你可以写

B[A] | C[not(A)]

同时记住,由于上下文节点不同,可能必须更改条件 A.

while remembering that the condition A may have to be changed because the context node is different.

如果要返回字符串,则代替

If you want to return strings, then in place of

if (A) then B else C

你可以使用可怕的解决方法

you can use the hideous workaround

concat(substring(B, 1, boolean(A) div 0), substring(C, 1, not(A) div 0))

这依赖于这样一个事实,即 (true div 0) 是正无穷大,而 (false div 0) 是 NaN.

which relies on the fact that (true div 0) is positive infinity, while (false div 0) is NaN.

(我想我是对的.我已经使用 XPath 1.0 多年了.但是有一些这样的表达方式是有效的.)

(I think I've got that right. It's years since I have used XPath 1.0. But there is some such expression that works.)

对于数字,您可以使用

B * boolean(A) + C * not(A)

回复 false=0,true=1.

replying on false=0, true=1.

对于多个条件像

if (A) then X else if (B) then Y else Z

你可以使用类似的逻辑,例如使用节点集它会变成

you can use similar logic, for example with node-sets it becomes

X[A] | Y[not(A) and B] | Z[not(A or B)]

这篇关于如果在 XPath 1.0 中的 else的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆