Stripping White Space Using normalize-space()

MSXML 5.0 SDK

Microsoft XML Core Services (MSXML) 5.0 for Microsoft Office - XSLT Developer's Guide

Stripping White Space Using normalize-space()

XSLT provides a built-in function, normalize-space(), that strips leading and trailing white space from a string and normalizes multiple successive white space characters to a single space. It takes one argument: a string or node-set (node-sets are converted to strings as necessary). If the argument is omitted, normalize-space() assumes the context node.

The following is an XML fragment with leading newline and tab characters following the <generouswhitespace> start tag. There are 10 trailing spaces and a newline preceding the </generouswhitespace> end tag, as follows:

<generouswhitespace>
There is a l     o    t of white         space here!           
</generouswhitespace>

The white space in this fragment can be normalized with the following XSLT template rule, which encloses the text content of the <generouswhitespace> element in brackets ([]).

<xsl:template match="generouswhitespace">
[<xsl:value-of select="normalize-space(.)" />]
</xsl:template>

The output appears as follows.

[There is a l o t of white space here!]

All leading white space has been trimmed, and each block of extraneous white space within the text node has been normalized to a single space.