Search code examples
xsltfxsl

How to Trim in xslt?


I want to trim whitespace left and right in :
<xsl:value-of select="Datas/Data[@key='Name']/string"/>

How can I do that?


Solution

  • 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).