I want to trim whitespace left and right
in :
<xsl:value-of select="Datas/Data[@key='Name']/string"/>
How can I do that?
I want to trim whitespace left and right
in :
<xsl:value-of select="Datas/Data[@key='Name']/string"/>
How can I do that?
Compare the @ricosrealm's solution, for XSLT2 users, with the @Dimitre's for XSLT1 (and check also the number of lines of the FXSL-trim). The regular expression replace function is so simple, spend less CPU-time and less programmer's time.
For XSLT1 users in 2013
If you is a XSLT1 user, is probably because you not have choice to use XSLT2. Example: PHP depends on LibXML2 implementatin, that stoped in the 1999 standard, not implements the 2007's standard. Today (2013) only a fraction of XSLT1 users do this by performance considerations.
So, if you assumes that you is trapped by XSLT1 and your framework, is time to know and to use "registered functions", like on PHP (but any other like Python or Javascript using LibXML2 can use LibXML2's extensions), to approximate to XSLT2 liberty/functionality.
See XSLTProcessor::registerPHPFunctions on your language.
PHP example:
NOTE (edited): for non-libXML2 implementations, like at Microsoft (.NET) frameworks, as showed by @ChristopheDebove (comments below), there are also solutions for registered functions. Of course, for Java there are SAXON, the only good open source of XSLT2 today.
... If one day (see opinions about when here and here) you replace XSLT1 by XSLT2 in the same framework (ex. PHP), you not need to change your XSLT scripts, because is expected that registred functions will be the same.
The easiest way is to use the
trim
template function of FXSL.This transformation:
when applied on this XML document:
produces the wanted, correct result:
How
trim
works:It is easy to eliminate all starting whitespace characters in a string, but the difficult part is to eliminate all ending whitespace characters.
The FXSL's
trim
function/template achieves this by using another template/function of FXSL for reversing a string.So, the processing goes like this:
Eliminate leading white-space.
Reverse the result.
Eliminate leading whitespace.
Finally reverse.
The full code for
trim()
in FXSL 2.0 (for XSLT 2.0) can be seen here. It is almost the same as the code for thetrim
template of FXSL 1.0 (for XSLT 1.0).Offering another solution that I use in XSLT 2.0 since it's more concise and accurate (normalize-space is not a trim).
Use the replace function and a regular expression to grab the inner content minus the preceding and trailing whitespace.
normalize-space(Datas/Data[@key='Name']/string)
might suffice, it will trim white space and the start and end. It does however also collapse any white space in between to a single space, I don't know whether you want that.