1. Overview

In this tutorial, we'll look at the identity template.

Identity template or identity transformation takes the input XML and writes to output without any changes. As a result, whenever we give an XML document, we get the same XML document back.

This can be a good starting point for several use cases. For example, we can override the transformation process for needed parts by providing additional templates.

2. Analysis

Let's first define the identity template:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="node() | @*">
    <xsl:copy>
      <xsl:apply-templates select="node() | @*"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

The XSLT pattern node() | @* selects the union of attribute nodes @* and all other types of XML nodes node(). If we use XSLT selection axes, it is equivalent to attribute::* | child::node().

In XSLT, XPath expressions are relative to the context node and the default selection axis is the child axis, so this expression

  • selects all attributes and immediate children of the context node (when used in a select="..." expression, for example in <xsl:apply-templates>)
  • matches all attributes and other nodes regardless of context (when used as a match="..."expression in <xsl:template>)

A special characteristic of XML is that attribute nodes are not children of the elements they belong to (although the parent of an attribute is the element it belongs to). This asymmetric relationship makes it necessary to select them separately, hence the @*.

When we feed the following input, the output will be the same.

<school>
  <class count="3">
    <teacher>John</teacher>
    <students>
      <student>Tom</student>
      <student>Kate</student>
      <student>Steve</student>
    </students>
  </class>
</school>