3

I have enabled XPath 2.0 configuration synapse.xpath.dom.failover.enabled=true in synapse.properties but still unable to get string padding done. Is there any expression to achieve it?

Edit :

The length of a particular string needs to be 10 chars, if it is lesser than it, we have to pad it with the special character '%'.

Eg., Input = 'WSO2', after padding it should be 'WSO2%%%%%%'

Thanks in advance

Community
  • 1
  • 1

2 Answers2

4

This can be achieved using XPath 1.0 like so, assuming that "WSO2" will be replaced by dynamic input string in the actual implementation :

substring(concat('WSO2', '%%%%%%%%%%'), 1, 10)

The above XPath basically works by concatenating string of 10 specific for-padding characters to the original input string, and then substring the result to get only the first 10 characters. Found this trick in the following XSL question : XSL left-right justification with Padding

To put this in a more generic formula :

substring(concat('input_string', '%%%%....'), 1, n)
  • input_string : string to which padding operation will applied
  • % : character used for padding, repeated n times
  • n : fixed number of characters expected in the output string
Community
  • 1
  • 1
har07
  • 88,338
  • 12
  • 84
  • 137
4

The solution from @har07 is fine if you have a reasonable upper bound on the value of n, but if you don't, you can create a string containing '%' repeated $n times using

XPath 3.0: string-join((1 to $n)!"%")

XPath 2.0: string-join(for $x in 1 to $n return "%", "")
Michael Kay
  • 156,231
  • 11
  • 92
  • 164
  • Hi Michael, Could you please explain the 2nd xpath above, please. – Vincent Nov 15 '16 at 09:40
  • 1
    `1 to $n` produces a sequence of numbers. `for $x in 1 to $n return "%"` produces a sequence of $n strings each of which is the string "%". string-join() joins a sequence of strings into a single string, with the second argument optionally providing a separator. – Michael Kay Nov 15 '16 at 12:01
  • 1. How do I add characters *before* the result? I now have `concat(string-join((1 to (10 - string-length('WSO2')))!\"0\"), 'WSO2')`. 2. Is there any chance to replace the redundant occurence of `'WSO2'`? In my case WSO2 is a longer expression (`tokenize(xr:Referenced_purchase_order_line_reference/text(), '[.]')[2]`). – bgerth Dec 13 '20 at 09:37
  • Please don't add a new supplementary question as a comment on an existing answer, especially one that's five years old. Ask a new question; reference this question if the reference adds value. – Michael Kay Dec 13 '20 at 11:48