Understanding the Basics of XSLT

Article includes a simple example to illustrate the basic operations of XSLT (Extensible Stylesheet Language Transformations), a part of the XSL family defined by the World Wide Web Consortium (W3C).

XSLT, or Extensible Stylesheet Language Transformations, is a part of the XSL family defined by the World Wide Web Consortium (W3C). You can find detailed information on their website. The W3C points to a tutorial here and there are lots of books that can help you learn it.

The purpose of this language is to read one XML file and produce a different XML or text file. Here's a short example:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>

<xsl:template match="*">
<xsl:apply-templates select="node()"/>

<xsl:template match="text()"/>

  • output indent="yes" - produce indented XML output
  • template match="*" - process each element at the current level in the XML input in turn *1
  • copy - copy the current element
  • apply-templates select="node()" - apply templates for each element that is a direct child of the current element (not exactly but close enough)
  • template match="text()" - if the current element is a text element, not an attribute and not a tag, do nothing *2

*1: This template gets used unless another later on in the stylesheet matches the current element
*2: This template is the only one that appears "later on". Because it contains no instructions, it produces no output.

For this input:

<?xml version="1.0" encoding="UTF-8"?>
Checking example.cc...
<error file="example.cc" line="5" id="unassignedVariable" severity="style" msg="Variable &apos;x&apos; is not assigned a value."/>
<error file="example.cc" line="6" id="uninitvar" severity="error" msg="Uninitialized variable: x"/>
Checking usage of global functions..
<error id="missingInclude" severity="style" msg="Cppcheck cannot find all the include files (use --check-config for details)"/>

The stylesheet produces this output:

<?xml version="1.0"?>