Web Technology - Old Questions

9.  Why do we need XSLT? Explain XSL<xsl:if> Element.

5 marks | Asked in 2074

XSLT (Extensible Stylesheet Language Transformations) provides the ability to transform XML data from one format to another automatically.  It is the recommended style sheet language for XML.

XSLT is far more sophisticated than CSS. With XSLT we can add/remove elements and attributes to or from the output file. We can also rearrange and sort elements, perform tests and make decisions about which elements to hide and display, and a lot more.

XSLT uses XPath to find information in an XML document.

<xsl:if> Element

The XSLT <xsl:if> element is used to specify a conditional test against the content of the XML file.

Syntax:

<xsl:if test="expression">  

  ...some output if the expression is true...  

</xsl:if>   

E.g.

<?xml version="1.0" encoding="UTF-8"?>

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

<xsl:template match="/">

  <html>

  <body>

  <h2>My CD Collection</h2>

  <table border="1">

    <tr bgcolor="#9acd32">

      <th>Title</th>

      <th>Artist</th>

      <th>Price</th>

    </tr>

    <xsl:for-each select="catalog/cd">

      <xsl:if test="price &gt; 10">

        <tr>

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

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

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

        </tr>

      </xsl:if>

    </xsl:for-each>

  </table>

  </body>

  </html>

</xsl:template>

</xsl:stylesheet>

The code above will only output the title and artist elements of the CDs that has a price that is higher than 10.