Wednesday, February 18, 2004

Wednesday and XML

Are we sure that it was a wednesday? It really felt more like a thursday to me. Anyways it was a day and that is good enough. I was about to wake up and take a deep breath. (and cough immediately afterwards) I'm not sure that I was completely ready for the day. But it came anyway and in the end I am glad I was a part of it.
Well on to more constructive things. XML and XSL. XML and XSL are a great way to handle some of the navigation choirs that we have to deal with day in and day out. For example you have a page that some users want links to sites, and other users want links to blogs. Why not keep all that data in one place.

<?xml-stylesheet type="text/xsl" href="links.xsl"?>
<link id="1" name="google" navlevel="1"></link>
<ink id="2" name="builder" navlevel="1"></link>
<link id="3" name="tech republic" navlevel="1"></link>
<link id="4" name="lockheed" navlevel="1"></link>

<link id="5" name="Computer Zen" navlevel="2"></link>
<link id="6" name="Chardy" navlevel="2"></link>
<link id="7" name="Adventures in Real Life" navlevel="2"></link>
<link id="8" name="Pixie Stitch" navlevel="2></link>
As you can see the site links have a navlevel of 1 and blog links have a navlevel of 2. Easy enough right. So how are we going to show these links to our users? This is where XSL comes in. What we are going to do is write an XSL that will show only the navlevel we specify, lets say navlevel 2. It would look something like this:

<?xml version="1.0" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="">
<xsl:template match="/">
<xsl:for-each select="/navroot/link[@navlevel='2']">
<xsl:attribute name="href"><xsl:value-of select="." /></xsl:attribute>
<xsl:value-of select="@name" />
<br />

What we see in this example is that the XSL is looping through all of the <link> elements and looking for the attribute navlevel='2' when if finds it, it writes and a href from the <link> element and the name attribute with in the link tag. So in the browser it looks something like this:
Computer Zen
Adventures in Real Life
Pixie Stitch

Let's go over the xsl in a little more detail of what the XSL is doing. First we are have the XSL loop through all of the link elements in the XML document and take an action when it finds a navlevel='2'. This is handled in the <xsl:for-each select="/navroot/link[@navlevel='2']">. Think of this as XSL's for loop. This was a fairly simple example of what can be done with XML and XSL but I hope that you find it helpful.

No comments: