Previous | Next | Indexes
Zvon > Tutorials > XSLT 2.0 Tutorial > Functions operating on strings (10/15) >

Normalization of whitespace characters in a string with normalize-space() function

The function translate-space() removes all leading and trailing whitespace characters (spaces, new lines, tabs) and replaces neighboring whitespace characters inside a string with a single space.

Output of this tutorial is formatted to HTML and browsers automatically coalesce neighboring whitespace characters. The visual appearance of the source code therefore does not correspond to actual source. The function translate() was used in this example to visualize changes. Spaces are replaced with "X", new lines with "Y" (entity 
).

XPAth 2.0 introduces function normalize-unicode() to normalize Unicode values. This function is useful for signs used in some languages but it is not useful for Czech characters.

XSLT

      <xsl:stylesheet
                  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                  version="2.0">
            <xsl:output  method="xml"
                        indent="yes"
                        omit-xml-declaration="yes"/>

            <xsl:template  match="/aaa">
                  <xxx>
                        <xsl:variable  name="x"> a b c </xsl:variable>
                        <xsl:text>|</xsl:text>
                        <xsl:value-of  select="$x"/>
                        <xsl:text>| - |</xsl:text>
                        <xsl:value-of  select="normalize-space($x)"/>
                        <xsl:text>|</xsl:text>
                  </xxx>
                  <yyy>
                        <xsl:text>|</xsl:text>
                        <xsl:value-of  select="translate(bbb,' ','X')"/>
                        <xsl:text>| - |</xsl:text>
                        <xsl:value-of  select="translate(normalize-space(bbb),' ','X')"/>
                        <xsl:text>|</xsl:text>
                  </yyy>
                  <zzz>
                        <xsl:text>|</xsl:text>
                        <xsl:value-of  select="translate(ccc,' &#xA;','XY')"/>
                        <xsl:text>| - |</xsl:text>
                        <xsl:value-of  select="translate(normalize-space(ccc),' &#xA;','XY')"/>
                        <xsl:text>|</xsl:text>
                  </zzz>
            </xsl:template>

      </xsl:stylesheet>
XML

      <aaa>
            <bbb> 1 2 3 </bbb>
            <ccc>1 2 3 </ccc>
      </aaa>
Output

      <xxx>| a b c | - |a b c|</xxx>
      <yyy>|XXXX1XXXX2XX3X| - |1X2X3|</yyy>
      <zzz>|1YYYYXXX2Y3YXXXY| - |1X2X3|</zzz>


Previous chapter: Arithmetics
Next chapter: Transforming strings with regular expressions
Previous page: Replacing characters in strings with translate function
Next page: Joining strings with concat