How xsl:strip-space Controls Whitespace in XSLT

The xsl:strip-space element is a top-level XSLT instruction used to remove whitespace-only text nodes from specified elements in a source XML document before template processing begins. By defining which elements should have their extraneous spaces, tabs, and line breaks removed, developers can prevent unwanted whitespace in the output, ensure accurate node counting, and simplify XPath navigation.

Understanding Whitespace-Only Text Nodes

In XML, text between tags that contains only formatting characters—such as carriage returns, line feeds, tabs, and standard spaces—is parsed as a text node. By default, XSLT processors preserve these whitespace-only nodes. This default behavior can introduce unexpected empty lines in the output or alter the results of XPath expressions like count(*) or position().

Syntax and Operation

The xsl:strip-space element is placed directly under the root <xsl:stylesheet> or <xsl:transform> element. Its primary attribute is elements, which takes a whitespace-separated list of element names or wildcards.

<xsl:strip-space elements="book author description" />

To strip whitespace from all elements in the source document, use the wildcard selector:

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

How the Stripping Process Works

During the transformation process, the XSLT processor applies whitespace handling in a specific sequence:

  1. Source Tree Construction: The XML document is parsed into an abstract node tree.
  2. Identification of Whitespace Nodes: The processor identifies text nodes that consist entirely of whitespace characters (ASCII space, tab, line feed, carriage return). Nodes containing any non-whitespace character are left untouched.
  3. Rule Matching: The processor checks the parent element of the whitespace-only text node against the rules defined in xsl:strip-space and xsl:preserve-space.
  4. Node Removal: If the parent element matches an xsl:strip-space pattern, the text node is stripped from the source tree before templates are matched or applied.

Interaction with xsl:preserve-space and xml:space

Whitespace stripping is subject to specific precedence rules:

Practical Benefits

Using xsl:strip-space streamlines XML transformations by: