XML and XSL

Introducing templates

The XML contains a single stock element which in turn contains four items. We use this structure to investigate how XSL processes nodes. The template is tested against every node in the input tree. When a match is made then the content of the template is output. Once a match is made the child nodes will not be considered unless an explicit instruction to do so is given. This is a simple transformation, it outputs a single constant value for every node matched.

XML

<?xml version="1.0"?>
<stock>
    <item price="50" legend="Pr-Burger" BarCode="E1"/>
    <item price="15" legend="Crisp S+V" BarCode="E5"/>
    <item price="15" legend="Crisp C+O" BarCode="E6"/>
    <item price="50" legend="Flat Cola" BarCode="E7"/>
</stock> 

XSL

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

  <xsl:template match="stock">
    <p>Found something!</p>
  </xsl:template>
</xsl:stylesheet>

Investigating xsl:value-of

Typically we need to consider two issues in a template:

We can decide which nodes match using match attribute of the xsl:template node - the content of this node determines what gets output. In this example we output the bar code and the description of each item.

XML

<?xml version="1.0"?>
<stock>
    <item price="50" legend="Pr-Burger" BarCode="E1"/>
    <item price="15" legend="Crisp S+V" BarCode="E5"/>
    <item price="15" legend="Crisp C+O" BarCode="E6"/>
    <item price="50" legend="Flat Cola" BarCode="E7"/>
</stock> 

XSL

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

  <xsl:template match="item">
    <p>
      <b><xsl:value-of select="@BarCode"/></b>:
         <xsl:value-of select="@legend"/>
    </p>
  </xsl:template>
</xsl:stylesheet>

Deciding what to show

We can use the match attribute to decide which nodes are considered. There are a number of ways of performing matches.

XML

<?xml version="1.0"?>
<stock>
    <item price="50" legend="Pr-Burger" BarCode="E1"/>
    <item price="15" legend="Crisp S+V" BarCode="E5"/>
    <item price="15" legend="Crisp C+O" BarCode="E6"/>
    <item price="50" legend="Flat Cola" BarCode="E7"/>
</stock> 

XSL

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

  <xsl:template match="item">
    <p>
      <b><xsl:value-of select="@legend"/></b>
    </p>
  </xsl:template>
</xsl:stylesheet>

Setting and using a variable

We create a variable and do some arithmetic on it.

XML

<catalogue shipping="3" tax="10">
  <album id="Blur" price="12"/>
  <album id="Travis" price="13"/>
</catalogue>

XSL

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

<xsl:variable name="s" select="//catalogue/@shipping"/>
<xsl:template match="album[@id='Blur']">
  <xsl:value-of select="@price + $s"/>
</xsl:template>

</xsl:stylesheet>