What Is Namespace Aliasing in XSLT?

Namespace aliasing in XSLT, implemented via the <xsl:namespace-alias> element, is a mechanism designed to output XSLT instructions or other specific XML namespaces without triggering execution during transformation. By mapping a temporary prefix used in the stylesheet to an intended result prefix in the output, it solves the fundamental conflict that arises when an XSLT stylesheet is used to generate another XSLT stylesheet.

The Problem: Generating XSLT with XSLT

When authoring a stylesheet that produces standard XML or HTML, elements matching the standard XSLT namespace ([http://www.w3.org/1999/XSL/Transform](http://www.w3.org/1999/XSL/Transform)) are treated as instructions to be executed by the XSLT processor. Any other element is treated as literal result element content and copied directly to the output.

However, when writing an XSLT stylesheet to generate another XSLT stylesheet (meta-programming or code generation), any element bearing the actual XSLT namespace prefix (such as <xsl:template>) is executed immediately rather than emitted as literal XML. Attempting to output XSLT syntax directly causes the processor to interpret those elements as instructions for the current transformation, leading to errors or malformed results.

How <xsl:namespace-alias> Works

The <xsl:namespace-alias> top-level element resolves this collision by allowing developers to declare a proxy or alias namespace for the generation phase and swap it with the target namespace during output generation.

The element takes two primary attributes:

During execution, the processor treats elements tied to the stylesheet-prefix as literal result elements. Upon serialization, the processor maps that namespace URI to the target URI defined by result-prefix.

Example Implementation

Consider a scenario where a stylesheet generates another stylesheet containing an <xsl:template> rule:

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:axsl="http://www.w3.org/1999/XSL/TransformAlias">

  <!-- Map the temporary 'axsl' prefix to the real 'xsl' namespace -->
  <xsl:namespace-alias stylesheet-prefix="axsl" result-prefix="xsl"/>

  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/">
    <!-- axsl elements are treated as literal output elements -->
    <axsl:stylesheet version="1.0">
      <axsl:template match="item">
        <axsl:value-of select="name"/>
      </axsl:template>
    </axsl:stylesheet>
  </xsl:template>

</xsl:stylesheet>

Transformation Result

When processed, the axsl namespace URI is replaced by the standard XSLT URI:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="item">
    <xsl:value-of select="name"/>
  </xsl:template>
</xsl:stylesheet>

Key Considerations