Quick and Dirty XSLT Primer


…From the Open Internet Lexicon: “A Transformation Language to convert XML/XSL documents into HTML suitable for a browser to display.” Personally, I like to think of it as language that sucks data from an XML file into an HTML file :).


Here’s a quick example that demonstrates how XSLT can be used in combination with HTML to build data-driven web pages.


 


XSLT Example:


Let’s say we have an XML file with three records, each the name of a breakfast food, and we want to display that data on a web page.


Here’s our XML file:
<?xml version=’1.0′?>
<BREAKFAST-MENU>
       <FOOD>
              <NAME>Eggs</NAME>             
       </FOOD>
       <FOOD>
              <NAME>French Toast</NAME>
       </FOOD>
       <FOOD>
              <NAME>Waffles</NAME>
       </FOOD>
</BREAKFAST-MENU>


Here’s what we want on the web page:






Breakfast Menu


Eggs


French Toast


Waffles


Using this XSLT (with inline HTML), we’ll get the right HTML:
<table border=”1″ width=”100%” cellpadding=”2″>
   
<tr valign=”top”>
       
<th nowrap=”true”><u>Breakfast Menu<u></th>
    </tr>
   
<xsl:for-each select=”/BREAKFAST-MENU/FOOD”>
        <tr>
            <td>
<xsl:value-of select=”NAME”/></td>
        </tr>
   
</xsl:for-each>
</table>


The final HTML (after the XSLT is processed):
<table border=”1″ width=”100%” cellpadding=”2″>
    <tr valign=”top”>
        <th nowrap=”true”><u>
Breakfast Menu<u></th>
    </tr>
    <tr>
        <td>
Eggs</td>
    </tr>
    <tr>
        <td>
French Toast</td>
    </tr>
    <tr>
        <td>
Waffles</td>
    </tr>
</table>


How it works:
When the XSL is processed, commands that begin with
<xsl:> get treated like programming commands. The for-each” statement causes the markup contained within the for-each to be processed once for each item that is returned by the select=”/BREAKFAST-MENU/FOOD” command, which is this case returns the three food records. The <xsl:value-of select=”NAME”/> command is what sucks the actual data from the XML file into the HTML. xsl:value-of food your best friend when it comes to understanding XSLT and particularly XSLT generated by FrontPage.


Next up: How the Data View uses XSLT.