Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If then else in XPath 1.0

Tags:

xml

xpath

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.

like image 338
TitanFighter Avatar asked Jan 07 '23 09:01

TitanFighter


1 Answers

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)]
like image 111
Michael Kay Avatar answered Jan 15 '23 01:01

Michael Kay