How to Trim in xslt?

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.

replace(Datas/Data[@key='Name']/string,'^\s*(.+?)\s*$', '$1')

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.


The easiest way is to use the trim template function of FXSL.

This transformation:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:import href="trim.xsl"/>
<xsl:output method="text"/>

  <xsl:template match="/">
    '<xsl:call-template name="trim">
        <xsl:with-param name="pStr" select="string(/*)"/>
    </xsl:call-template>'
  </xsl:template>
</xsl:stylesheet>

when applied on this XML document:

<someText>

   This is    some text   

</someText>

produces the wanted, correct result:

'This is    some text'

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:

  1. Eliminate leading white-space.

  2. Reverse the result.

  3. Eliminate leading whitespace.

  4. 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 the trim template of FXSL 1.0 (for XSLT 1.0).

Tags:

Xslt

Fxsl