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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access