Show Menu
Cheatography

XSLT Cheat Sheet (DRAFT) by

XSLT Cheat Sheet. Information shared by w3schools.com.

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Overview

XSLT stands for XSL Transfo­rma­tions
XSLT uses XPath to navigate in XML documents
XSLT transforms an XML document into another XML document
To declare an XSL style sheet use one of the following
-
<xs­l:s­tyl­esheet versio­n="1.0" xmlns:­xsl­="ht­tp:­//w­ww.w­3.o­rg­/19­99/­XSL­/Tr­ans­for­m">

-
<xs­l:t­ran­sform versio­n="1.0" xmlns:­xsl­="ht­tp:­//w­ww.w­3.o­rg­/19­99/­XSL­/Tr­ans­for­m">
Note:
<xs­l:s­tyl­esh­eet>
and
<xs­l:t­ran­sfo­rm>
are completely synonymous and either can be used!

XSL Elements

<xs­l:s­tyl­esh­eet>
Defines this document as an XSLT style sheet
<xs­l:t­emplate match=­"­/">
Used to build templates. Use the match attribute to select elements with XPath. Content defines HTML to output.
<xs­l:v­alue-of select­"­/">
Used to extract the value of an XML element and add it to the output. Use the select attribute to select elements with XPath.
<xs­l:f­or-each select­="/">
Used to select every XML element of a specified node-set. Wrap elements containing
<xs­l:v­alu­e-o­f>
(Loop)
<xs­l:sort select­="/">
Used to sort the output.
<xsl:if test="expression">
Used to put a condit­ional if test against the content of the XML file. Add inside for-each tags to add a condition to the loop.
<xs­l:c­hoo­se>
Used in conjun­ction with
<xs­l:w­hen>
and
<xs­l:o­the­rwi­se>
to express multiple condit­ional tests. Wrap around these tags like if {...} else {...}.
<xs­l:when test="expression">
The IF or ELSE IF component of a choose statement. Multiple can be used back to back within
<xs­l:c­hoo­se>
<xs­l:o­the­rwi­se>
The ELSE component of a choose statement.
<xs­l:a­ppl­y-t­emp­lates select­="/">
Used to apply a template to the current element or to the current element's child nodes.
Note: You can filter the output from the XML file by adding criterion to the select attribute in the <xs­l:f­or-­eac­h> element.

Example:
<xs­l:f­or-each select­="ca­tal­og/­cd[­art­ist­='Bob Dylan'­]">


Legal operators are =, !=, &lt (<), &gt (>)
 

Templa­te/­App­ly-­Tem­plates Example

<xsl:template match="/">
  <html>
  <body>
  <h2>My CD Collection</h2>
  <xsl:apply-templates/>
  </body>
  </html>
</xsl:template>

<xsl:template match="cd">
  <p>
  <xsl:apply-templates select="title"/>
  <xsl:apply-templates select="artist"/>
  </p>
</xsl:template>

<xsl:template match="title">
  Title: <span style="color:#ff0000">
  <xsl:value-of select="."/></span>
  <br />
</xsl:template>

<xsl:template match="artist">
  Artist: <span style="color:#00ff00">
  <xsl:value-of select="."/></span>
  <br />
</xsl:template>