XML technologies / XSLT / Introduction to XSLT 2.0 / XSLT and XPath – getting started / Structure controls processing / Remove whitespace: xsl:strip-space

(Excerpt from “XSLT 2.0 & XPath 2.0” by Frank Bongers, chapter 1.)

Our discussion of the processing model explained when and why whitespace nodes from the source document appear in the result. An explicit template rule for text() could override the default rule and prevent copying. However, this also prevents the elegant method of processing text nodes indirectly through a sequence of xsl:apply-templates.

Fortunately, a better method exists: a declaration that discards whitespace nodes, xsl:strip-space. Place it at the beginning of the stylesheet too.

The required attribute identifying source elements whose contents should have whitespace removed is ele­ments:

<xsl:strip-space elements="adresse"/>

As used above, the declaration removes whitespace nodes within elements <adresse>, including their children. Multiple element names can be supplied as a space-separated list:

<xsl:strip-space elements="adresse name anschrift"/>

Instead of listing every element that might appear in a document, whitespace removal can be requested globally for all elements. Simply use the wildcard name:

<xsl:strip-space elements="*"/>

Applied to the address directory, this removes many annoying line breaks, but also useful whitespace nodes. The whitespace between information items is unintentionally deleted too:

<?xml version="1.0" encoding="ISO-8859-1"?>
<html>
  <head>
    <title>Adressenliste</title>
  </head>
  <body>
    <h1>Adressenliste</h1>
    <p>Name: <b>PeterMustermann</b><br />Anschrift:
                       12345BeispielshausenWagenstr.5a
    </p>
    <hr />
    ...

Code example: kap01/1.17.9/adressen.html.

There are two options: either change the template rules to output the required spaces using xsl:text or something similar, or step back a little.

The latter could mean replacing the global wildcard * in xsl:strip-space with an explicit, potentially lengthy list of element names, which was what we wanted to avoid. This is not straightforward anyway, since whitespace stripping applies to an element’s entire contents. Fortunately, there is a solution here too.

   

back to top