What is xsl:preserve-space in XSLT Transformations?

The xsl:preserve-space element in XSLT is a top-level instruction used to control whitespace handling by telling the XSLT processor to retain whitespace-only text nodes for specified elements in the source XML document. By default, XSLT processors preserve all whitespace, but when whitespace stripping is globally enabled using xsl:strip-space, xsl:preserve-space acts as an explicit exception mechanism to ensure formatting, indentation, and line breaks are maintained where needed.

The Role of Whitespace in XML and XSLT

XML documents often contain whitespace—such as spaces, tabs, and carriage returns—used for formatting and readability. When an XSLT processor parses an XML tree, these spaces are treated as text nodes. If an element contains only whitespace, it is designated as a whitespace-only text node.

Unwanted whitespace can bloat output, disrupt layout, or complicate template matching. Consequently, developers frequently use <xsl:strip-space elements="*"/> to remove all whitespace-only nodes across the entire document.

How xsl:preserve-space Works

The xsl:preserve-space element counteracts whitespace stripping for designated elements. It instructs the processor that any whitespace-only text nodes appearing inside the specified element tags must remain part of the source tree.

Syntax

The element is placed at the top level of the stylesheet (as a child of <xsl:stylesheet> or <xsl:transform>):

<xsl:preserve-space elements="element-name-1 element-name-2 ..." />

Common Use Cases

  1. Preformatted Content: Retaining formatting inside elements that represent code blocks, terminal outputs, or preformatted text (similar to the <pre> tag in HTML).
  2. Text Alignment and Poetry: Preserving intentional line breaks and stanza indentation in literary texts.
  3. Data Integrity: Ensuring that data fields where leading, trailing, or standalone whitespace has semantic value are not altered during transformation.

Precedence and Conflict Resolution

When both xsl:strip-space and xsl:preserve-space are used in the same stylesheet, the processor resolves conflicts using standard XSLT priority rules: