XSLT Cheat Sheet

Here’s a cheat sheet for XSLT (Extensible Stylesheet Language Transformations):

1XSLT Basics

<!-- XSLT stylesheet declaration -->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

<!-- Template to match elements -->
<xsl:template match="element_name">
  <!-- Transformation logic goes here -->
</xsl:template>

<!-- Apply templates -->
<xsl:apply-templates/>

<!-- Copy all content by default -->
<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>
</xsl:stylesheet>

Selecting Nodes

<!-- Select all child nodes -->
<xsl:apply-templates select="*"/>

<!-- Select nodes with a specific name -->
<xsl:apply-templates select="element_name"/>

<!-- Select nodes with a specific attribute -->
<xsl:apply-templates select="element[@attribute='value']"/>

Output Elements and Text

<!-- Output an element with a specific name -->
<xsl:element name="new_element">
  <!-- Content goes here -->
</xsl:element>

<!-- Output text content -->
<xsl:text>Text Content</xsl:text>

Variables and Parameters

<!-- Declare a variable -->
<xsl:variable name="var_name" select="expression"/>

<!-- Use a variable in a template -->
<xsl:value-of select="$var_name"/>

Conditional Processing

<!-- Apply templates if a condition is true -->
<xsl:if test="condition">
  <!-- Transformation logic -->
</xsl:if>

<!-- Apply templates if a condition is false -->
<xsl:if test="not(condition)">
  <!-- Transformation logic -->
</xsl:if>

For Each Loop

<!-- Loop through a set of nodes -->
<xsl:for-each select="nodes">
  <!-- Transformation logic for each node -->
</xsl:for-each>

Attribute Value Templates

<!-- Output an attribute with a dynamic value -->
<element_name attribute="{dynamic_value}"/>

Copying Nodes

<!-- Copy the current node -->
<xsl:copy>
  <xsl:apply-templates select="@*|node()"/>
</xsl:copy>

<!-- Copy a specific node -->
<xsl:copy-of select="node_to_copy"/>

Number Formatting

<!-- Format numbers -->
<xsl:value-of select="format-number(number, 'format')"/>

Sorting Nodes

<!-- Sort nodes by a specific criteria -->
<xsl:apply-templates select="nodes">
  <xsl:sort select="sort_criteria"/>
</xsl:apply-templates>

Namespace Handling

<!-- Define a namespace alias -->
<xsl:stylesheet xmlns:x="namespace_uri" ...>

<!-- Use the namespace alias -->
<xsl:value-of select="x:element_name"/>

Commenting

<!-- Add comments in XSLT -->
<!-- This is a comment -->

These commands cover some common tasks when working with XSLT. For more details and advanced usage, refer to the official W3C XSLT Recommendation.