Converting XML to HTML using XSL

Example 1:

In this example we will write a XSL template for our XML. When placing this example online you will see a HTML page but with the *.xml extension!

Preparing the XML file

In this part we need to tell our XML file where it can find the XSL template. Save this file as "mystore.xml".

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="XSLcdstore.xsl"?>

<cdstore>

  <cd>
    <title>R.E.M. Live</title>
    <artist>R.E.M.</artist>
    <price>19.60</price>
  </cd>

  <cd>
    <title>The Art of Love and War</title>
    <artist>Angie Stone</artist>
    <price>13.64</price>
  </cd>

</cdstore>
Creating the XSL template

This file will tell us how our page should look. We choose for a simple HTML table. You can change the file if you want it to look different. Save this file as "XSLcdstore.xsl" (It should be the same name as in the mystore.xml file).

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

  <xsl:template match="/">

    <html>
      <head>
        <title>My cd store</title>
      </head>
      <body>
        <h1>My cd store</h1>

        <table border="0">
          <tr bgcolor="#9acd32">
            <th>CD Title</th>
            <th>Artist</th>
            <th>Price</th>
          </tr>

          <xsl:for-each select="cdstore/cd">
            <tr>
              <td><xsl:value-of select="title"/></td>
              <td><xsl:value-of select="artist"/></td>
              <td><xsl:value-of select="price"/></td>
            </tr>
          </xsl:for-each>
        </table>
      </body>
    </html>

  </xsl:template>
</xsl:stylesheet>
The result

Save "mystore.xml" into your webfolder or open it with your webbrowser. You will see a nice basic table with CDs.