I encountered a great trick in a forum post; this post also referred to Becker’s Method. In short, the trick uses the fact that the numerical evaluation of (Boolean) true = 1 and of false = 0. It also makes use of the fact that substring( somestring, 1, 0) returns an empty string.
The abstract XPath expression used for
if C1 then R1 else R2
concat( substring( R1, 1,number (C1) * string-length(R1), substring( R2, 1, number(not(C1)) * string-length(R2)
when R1 and R2 are not of type string, then some type conversion to and from string are required.
An example of using this trick:
In a Mediator component I want to assign the value ‘LONG’ when the input string is longer than 6 characters. When the stringlength is 6 or less, then I want to assign the value not long.
With the ternary expression, this would be something like:
result = (input.length() > 6? ‘LONG’: ‘NOTLONG’)
The corresponding XPath expression is this:
substring( ‘LONG’, 1, ( number(string-length($in.payload/client:process/client:input) > 6) * 4))
, substring( ‘NOTLONG’, 1, ( number(string-length($in.payload/client:process/client:input) <= 6) * 7))
6 thoughts on “How to create an if-then-else expression (aka ternary operator) in an XPath 1.0 expression?”
Excellent trick ! Thanks for this great post. I always tent use xsl transform when I needed a ternary operation in my assign.
thanks man, this is genius.
Wow!! I wanted to separate emails by commas but i didn’t want the comma in the beginning, of course. Following your method i did this in my “for each” and it worked : substring(‘,’, 1, ($mailCounter > 1)). The condition returns 0 and a substring from one to zero returns empty so the comma is not added in the beginning. Great
Hi Gabriel, thank you for your comment. It is nice to know that this was useful for you. Lucas
awesome Lucas. I love your SOA book. You rock always !!!
Wow, this is realy great. I wished I knew this one years ago. There has been so many situations where I could have used this.
Comments are closed.