How Does XSLT Handle Whitespace Stripping?

In XSLT processing, whitespace handling directly affects the structure of the input document's tree before templates are applied. The <xsl:strip-space> and <xsl:preserve-space> top-level elements control whether text nodes consisting purely of whitespace characters—such as spaces, tabs, line feeds, and carriage returns—are retained or stripped from selected elements in the source document. Managing these nodes is essential for cleaning up formatting artifacts, ensuring accurate node indexing, and preventing unwanted whitespace from leaking into output transformations.

The Default Whitespace Behavior

By default, an XSLT processor preserves all whitespace-only text nodes present in the source XML document unless explicitly instructed otherwise. In standard processing rules:

Because an XSLT processor considers whitespace-only text nodes as full child nodes in the XPath data model, leaving them intact affects functions like count(*), position(), and axis navigation like following-sibling::node().

Using <xsl:strip-space>

The <xsl:strip-space> element instructs the XSLT processor to remove whitespace-only text nodes from the specified elements before any template matching occurs.

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

Key aspects of whitespace stripping:

  1. Targeted Elements: The elements attribute accepts a whitespace-separated list of NameTests, such as specific element names, wildcards (*), or qualified names with namespaces.
  2. Whitespace-Only Nodes Only: It removes text nodes that consist entirely of whitespace characters (U+0020, U+0009, U+000D, U+000A). If a text node contains even a single non-whitespace character, it is entirely preserved.
  3. Tree Modification: The removal occurs during tree construction. Stripped nodes do not exist in the source tree viewed by subsequent XPath expressions and template rules.

Using <xsl:preserve-space>

The <xsl:preserve-space> element explicitly specifies which elements must retain their whitespace-only text nodes. This is primarily used to override broader stripping rules.

<xsl:strip-space elements="*"/>
<xsl:preserve-space elements="code pre formatted-text"/>

In this pattern, all elements across the source document have their whitespace-only text nodes stripped, except for <code/>, <pre/>, and <formatted-text/>, where exact source formatting must remain intact.

Conflict Resolution and Priority

When elements match conflicting declarations, XSLT resolves them using conflict resolution rules based on import precedence and pattern priority:

Impact on XPath Operations

Whitespace manipulation significantly alters XPath evaluations: