XSLT follows a set of rules in order to convert XML to another document. The rules are called a template and are applied when a node of particular type or content is found. The description below, followed by example explain the template rule.

The <xsl:stylesheet> and <xsl:transform>

The elements above declare the XSL stylesheet. Any of the above elements can be used to declare stylesheet in the XSLT document.

Syntax for XSL stylesheet:

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

or:

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

The <xsl:template>

The <xsl:template> element as the name explains builds templates. The match attribute is used to match the template with content of an XML document. The XPath expression is used for the match attribute and it defines the template for the node axis given in expression. A '/’ represents the whole document or a root node.

Syntax for <xsl:template> and match attribute

<xml version …>

<xsl:template match=”/”>

<html>

.

.

</html>

The <xsl:value-of>

The xsl:value-of element gives the value of the selected node. That node can be used in the output stream for transformation. The select attribute contains XPath expression or node value as in the example below.

Syntax for <xsl:value-of> and select attribute

<html>

.

<td><xsl:value-of select=”to”></td>

<td><xsl:value-of select=”movie/name”></td>

.

</html>

The <xsl:for-each>

The <xsl:for-each> element can be used to select every XML element in a node set. The output can be filtered by using selection criterion.

Syntax for <xsl:for-each> and select attribute

<html>

.

<xsl:for-each select="inbox/note">

<!—Selects only message to bossà

<xsl:for-each select="inbox/note[to=’boss’]">

.

</html>

The <xsl:sort>

The <xsl:sort> element sorts the output of a document. It can be added within the for-each element to get the output sorted.

Syntax for <xsl:sort> and select attribute

<html>

.

<xsl:for-each select="inbox/note">

      <xsl:sort select=”to” />

      <tr>

        <td><xsl:value-of select="to"/></td>

        <td><xsl:value-of select="from"/></td>

        <td><xsl:value-of select="msg"/></td>

      </tr>

.

</html>

The <xsl:if>

The <xsl:if> element puts a conditional test against the content of the XML file. The test attribute contains the expression to be evaluated.

Syntax for <xsl:if> and select attribute

<html>

.

<xsl:for-each select="inbox/note">

      <xsl:if test=”to=’boss’” />

      <tr>

        <td><xsl:value-of select="to"/></td>

        <td><xsl:value-of select="from"/></td>

        <td><xsl:value-of select="msg"/></td>

      </tr>

.

</html>

Example of XSLT document conversion

 

›› go to examples ››