The normalize-space() function
Another useful technique for controlling whitespace is
the normalize-space()
function.
In our previous example, we used <xsl:preserve-space>
and <xsl:strip-space>
to control
whitespace nodes in various elements, but we still have quite a bit of
whitespace in the name
attribute
and the last <car>
in the
list. To clean up the whitespace, we can use the normalize-space()
function. It does
three things:
It removes all leading spaces.
It removes all trailing spaces.
It replaces any group of consecutive whitespace characters with a single space.
We’ll use normalize-space()
in this
stylesheet:
<?xml version="1.0"?>
<!-- normalize-space.xsl -->
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<xsl:apply-templates />
</xsl:template>
<xsl:template match="*">
<xsl:copy>
<xsl:for-each select="@*">
<xsl:attribute name="{name()}">
<xsl:value-of select="normalize-space()"/>
</xsl:attribute>
</xsl:for-each>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="text()">
<xsl:value-of select="normalize-space()"/>
</xsl:template>
</xsl:stylesheet>
This stylesheet generates these crowded results:
<?xml version="1.0" encoding="UTF-8"?><cars><manufacturer name="Chevr olet"><car>Cavalier</car><car>Corvette</car><car>Impala</car><car>Mon te Carlo</car></manufacturer></cars>
This removes all the extraneous whitespace from the name
attribute and the <car>
element; it also effectively removes the whitespace-only ...
Get XSLT, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.