If then else in XPath 1.0

自闭症网瘾萝莉.ら 提交于 2020-05-13 06:35:17

问题


I have the next expression:

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())

which returns 'True'.

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

How to make the logic like:

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.


回答1:


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

you can write

B[A] | C[not(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))

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

(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.)

For numbers, you can use

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

replying on false=0, true=1.

For a multiple conditional like

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)]


来源:https://stackoverflow.com/questions/36191585/if-then-else-in-xpath-1-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!