If then back in XPath 1.0

I have the following 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 the values of the 1st and 2nd paths, for example ['11 061 886', '▼'].

How to make 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 I can not find the answer.

+4
source share
1 answer

If you really can't find the XPath 2.0 processor, there are some workarounds in XPath 1.0 that might work for you.

If you want to select node-sets, instead

if (A) then B else C

You can write

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

remembering that condition A can be changed because the context of the node is different.

If you want to return the rows, instead

if (A) then B else C

you can use a disgusting workaround

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

, ( div 0) , (false div 0) NaN.

( , . , XPath 1.0, , .)

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

false = 0, true = 1.

,

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

, , node -sets,

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

All Articles