View Full Version : Help with XSLT variables & for-each loop

08-29-2008, 03:00 PM
I'm working on creating an XSL stylesheet to display some sports statistics (currently in XML) in a table. Here's what the XML looks like:


<Player pID=101>
<Stat Type="stat1">2</Stat>
<Stat Type="stat2">5</Stat>
<Stat Type="stat3">5</Stat>
<Player pID=102>
<Stat Type="stat2">3</Stat>
<Stat Type="stat4">8</Stat>
<Stat Type="stat5">1</Stat>
<Player pID=103>
<Stat Type="stat1">2</Stat>
<Stat Type="stat2">6</Stat>
<Stat Type="stat4">3</Stat>
As you can see, there are several stat types available. Not all players have all of them, and if nothing is listed for a particular type, they should be set to 0. Ideally, the table would look something like this:

pID stat1 stat2 stat3 stat4 stat5
101 2 5 5 0 0
102 0 3 0 8 1
103 2 6 0 3 0
This is what I have so far:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<xsl:variable name="statlist" select="Lineup/Player/Stat/@Type[not(.=following::Player/Stat/@Type)]" />
<table border="1">
<th align="left">pID</th>
<xsl:for-each select="$statlist">
<th align="left"><xsl:value-of select="."/></th>
<xsl:for-each select="Lineup/Player">
<td><xsl:value-of select="@pID"/></td>
<xsl:for-each select="$statlist">
<td><xsl:value-of select="Stat[@Type='$statlist']"/></td>
Since each stat type appears multiple times in the XML page, I needed to make sure I only had unique items. This seems to work ok, and all of them show up in the table headers. I'm having trouble getting the data to display in the table, though. Unfortunately, I have no idea where to begin troubleshooting this, so here I ask for another set of eyes. Am I on the right track, or is there a better way of doing this?