I am newbie to xslt. My requirement is to transform xml file into text file as per the business specifications. I am facing an issue with one of the string formatting issue. Please help me out if you have any idea.
Here is the part of input xml data: "0001295"
Expected result to print into text file: 1295
My main issue is to remove leading Zeros. Please share if you have any logic/function.
Here is one way you could do it in XSLT 1.0.
First, find the first non-zero element, by removing all the zero elements currently in the value
Then, you can find the substring-before this first character, and then use substring-after to get the non-zero part after this
Or, to combine the two statements into one
So, given the following input
Then using the following XSLT
The following will be output
All XSLT1 parser, like the popular libXML2's module for XSLT, have the registered functions facility... So, we can suppose to use it. Suppose also that the language that call XSLT, is PHP: see this wikibook about registerPHPFunctions.
The build-in PHP function
ltrim
can be used inNow imagine a little bit more complex problem, to
ltrim
a string with more than 1 number, ex.hello 002 and 021, bye
.The solution is the same: use registerPHPFunctions, except to change the build-in function to a user defined one,
converts the example into
hello 2 and 21, bye
.As a simple alternative in XSLT 2.0 that can be used with numeric or alpha-numeric input, with or without leading zeros, you might try:
This works because
^0*
is greedy and(..*)
captures the rest of the input after the last leading zero.$1
refers to the captured group.Note that an input containing only zeros will output
0
.XSLT 2.0 Remove leading zeros from STRING
Just use this simple expression:
Here is a complete example:
When applied on this XML document:
the wanted, correct result is produced:
II. Use
format-number()
There are a couple of ways you can do this. If the value is entirely numeric (for example not a CSV line or part of a product code such as ASN0012345) you can convert from a string to a number and back to a string again :
Otherwise just replace the 0's at the start :
The '^' is required (standard regexp syntax) or a value of 001201 will be replaced with 121 (all zero's removed).
Hope that helps. Dave