If you don’t have time to read and want a working code template, then the following piece of code is your solution:

concat( substring($s1, 1, number($condition) * string-length($s1)), substring($s2, 1, number(not($condition)) * string-length($s2)) )

If you want to understand how it works please continue reading.

In XPATH 2.0 there is a conditional function that looks like this:

if (test-expression) then expression else expression

In XPATH 1.0 there is no such out of the box function that creates if-then-else statement.

So we have to be creative and use our imagination. This method is also known as “Becker’s method”.

The whole method relies on concatenation of 2 mutually exclusive strings. So in the end only one of them will be the result of the concatenation.

First let’s see how the following functions work:



The substring() function accepts the following parameters: string, start index and end index. If we substring from 1 to the string’s length then we will get the initial string. If we substring from 1 to 0 we ll get nothing. The number() function takes a parameter and returns its number representation. So when we pass a condition i.e @attr='foo' if the attribute value is 'foo' then the $condition is true and its number representation is 1,on the other hand if the $condition is false then its number representation is 0. The concat() function accepts several string parameters and joins the min one string. If one of the strings is empty it is omitted.

In the end, when we combine all these functions well get something like this:

concat( substring('FOO', 1, number(@attr='foo') * string-length($s1)), substring('BAR', 1, number(not(@attr='foo')) * string-length($s2)) )

If the attribute is foo then the function will produce ‘FOO’ because it will be evaluated as follows:

1. Step

concat substring('FOO', 1, number(@attr='foo') * string-length($s1)), substring('BAR', 1, number(not(@attr='foo')) * string-length($s2)) )

2. Step

concat( substring('FOO', 1, number(true) * string-length('FOO')), substring('BAR', 1, number(not(true)) * string-length('BAR')) )

3. Step

concat( substring('FOO', 1, 1 * 3), substring('BAR', 1, 0 * 3) )

4. Step

concat('FOO','')

5.Step

'FOO'

If the attribute is not ‘foo’ then the output will be ‘BAR‘.

Thank you for reading!