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"?>
<navroot>
<link id="1" name="google" navlevel="1">http://www.google.com</link>
<ink id="2" name="builder" navlevel="1">http://www.builder.com</link>
<link id="3" name="tech republic" navlevel="1">http://www.techrepublic.com</link>
<link id="4" name="lockheed" navlevel="1">http://www.lockheedfcu.org</link>

<link id="5" name="Computer Zen" navlevel="2">http://www.computerzen.com</link>
<link id="6" name="Chardy" navlevel="2">http://chardy101.blogspot.com</link>
<link id="7" name="Adventures in Real Life" navlevel="2">http://o2bjang.blogspot.com</link>
<link id="8" name="Pixie Stitch" navlevel="2>http://pixiesitch.blogspot.com</link>
</navroot>
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="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<xsl:for-each select="/navroot/link[@navlevel='2']">
<a>
<xsl:attribute name="href"><xsl:value-of select="." /></xsl:attribute>
<xsl:value-of select="@name" />
</a>
<br />
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>


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
Chardy
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: