如果然后在XPath 1.0中

Tit*_*ter 4 xml xpath

我有下一个表达式:

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())
Run Code Online (Sandbox Code Playgroud)

返回'True'.

如果我使用"|" 而不是'或',它组合了第一和第二路径的值,就像这样['11 061 886', '?'].

如何使逻辑像:

If the 1st path exists:
    get the 1st value
elif the 2nd path exists:
    get the 2nd value
else:
    pass
Run Code Online (Sandbox Code Playgroud)

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

Mic*_*Kay 7

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

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

if (A) then B else C
Run Code Online (Sandbox Code Playgroud)

你可以写

B[A] | C[not(A)]
Run Code Online (Sandbox Code Playgroud)

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

如果你想返回字符串,那么代替

if (A) then B else C
Run Code Online (Sandbox Code Playgroud)

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

concat(substring(B, 1, boolean(A) div 0), substring(C, 1, not(A) div 0))
Run Code Online (Sandbox Code Playgroud)

这取决于(真正的div 0)是正无穷大的事实,而(假div 0)是NaN.

(我想我已经做对了.自从我使用XPath 1.0以来已经有好几年了.但是有一些这样的表达式可行.)

对于数字,您可以使用

B * boolean(A) + C * not(A)
Run Code Online (Sandbox Code Playgroud)

回复false = 0,true = 1.

对于多条件而言

if (A) then X else if (B) then Y else Z
Run Code Online (Sandbox Code Playgroud)

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

X[A] | Y[not(A) and B] | Z[not(A or B)]
Run Code Online (Sandbox Code Playgroud)

  • 我对你表示同情。 (3认同)