Using <xsl:preserve-space> and <xsl:strip-space>
The XSLT spec gives us two ways of dealing with
whitespace nodes. We can use the <xsl:preserve-space>
and <xsl:strip-space>
nodes to keep or
delete whitespace. Here’s a slightly modified version of our
stylesheet:
<?xml version="1.0"?> <!-- copy-of-whitespace.xsl --> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:preserve-space elements="manufacturer"/> <xsl:strip-space elements="cars"/> <xsl:template match="/"> <xsl:copy-of select="."/> </xsl:template> </xsl:stylesheet>
Here’s what we get when we process our list of cars with the modified stylesheet:
<?xml version="1.0" encoding="UTF-8"?><!-- carlist_whitespace.xml --><cars> <manufacturer name=" Chevrolet "> <car>Cavalier</car> <car>Corvette</car> <car>Impala</car> <car>Monte Carlo</car> </manufacturer></cars>
In the result document, the whitespace nodes inside the <cars>
element have been removed,
while all the whitespace inside the <manufacturer>
element has been
preserved. (The complete text of
the <manufacturer>
element scrolls off the
right side of the page.) You can use <xsl:preserve-space>
and <strip-space>
with wildcards as well:
<xsl:preserve-space elements="cars manufacturer"/> <xsl:strip-space elements="*"/>
This tells the XSLT processor to strip whitespace nodes on all
the elements except the <cars>
and <manufacturer>
elements. The elements
attribute can contain an asterisk
or a space-separated list of element names.
Note
Because 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.