Partager via


Using the Normalize-space() Function

A version of this page is also available for

Windows Embedded CE 6.0 R3

4/8/2010

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, which is converted to a string 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.

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

This fragment's white space can be normalized with the following XSLT template rule, which encloses the <generouswhitespace> element's text content in [ ] characters.

<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 formatted to a single space.

See Also

Concepts

Controlling White Space with XSLT