Built-in Template Rules in XSLT Explained
This article explains built-in template rules in XSLT, which serve as default behaviors defined by the W3C specification to ensure every node in an input XML document is processed even when no explicit matching template exists in a stylesheet. Understanding these fallback mechanisms clarifies why certain text appears in transformation outputs by default and how to control recursive XML traversal.
What Are Built-in Template Rules?
In XSLT, template matching drives the transformation process. When
the XSLT processor encounters a node in the source XML tree, it searches
the stylesheet for an <xsl:template match="..."> rule
that corresponds to that node. If no user-defined template matches the
node, the processor does not produce an error; instead, it executes a
built-in template rule tailored to that specific node
type.
Processing of Unmatched Nodes by Node Type
Built-in template rules behave differently depending on the kind of XML node being processed:
1. Element and Root Nodes
For document root nodes (/) and element nodes
(*), the built-in rule recursively instructs the processor
to apply templates to all child nodes.
Equivalent explicit syntax:
<xsl:template match="*|/">
<xsl:apply-templates/>
</xsl:template>Because of this rule, the processor traverses deeper into the XML tree hierarchy, searching for matching templates on child elements until it reaches leaf nodes (text nodes).
2. Text and Attribute Nodes
For text nodes (text()) and attribute nodes
(@*), the built-in rule copies the string value of the node
directly to the output result tree.
Equivalent explicit syntax:
<xsl:template match="text()|@*">
<xsl:value-of select="."/>
</xsl:template>This is why an empty or minimal XSLT stylesheet outputs all the text content of an XML document: elements are traversed recursively by default, and text nodes are copied to the output.
3. Processing Instructions and Comments
For processing instructions and comment nodes, the built-in rule performs no action, effectively ignoring them.
Equivalent explicit syntax:
<xsl:template match="processing-instruction()|comment()"/>4. Namespace Nodes
Similar to comments and processing instructions, built-in rules ignore namespace nodes unless explicitly queried.
Overriding Built-in Templates
Because built-in templates have the lowest priority, any user-defined
<xsl:template> will automatically override them.
To suppress the default text-copying behavior across an entire document, add an empty text template:
<xsl:template match="text()"/>To stop recursive traversal through specific elements, define an empty template matching those element names:
<xsl:template match="IgnoredElement"/>
By relying on or overriding these defaults, developers can precisely manage which parts of an XML structure are preserved, transformed, or discarded during processing.