Inside Xslt
Reading Attribute Values
To refer to an attribute value using XPath, you preface the attribute name with @ like this: "@src" , "@height" , "@width" , and so on. To match any attribute, you can use the expression "@*" . To refer to the UNITS attribute in each <MASS> , <RADIUS> , and <DAY> element, you can use the expression "@UNITS" . That means you can recover and display the units used for each measurement in planets.xml this way:
Listing 3.3 Reading Attribute Values
<?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/PLANETS"> <HTML> <HEAD> <TITLE> The Planets Table </TITLE> </HEAD> <BODY> <H1> The Planets Table </H1> <TABLE BORDER="2"> <TD>Name</TD> <TD>Mass</TD> <TD>Radius</TD> <TD>Day</TD> <xsl:apply-templates/> </TABLE> </BODY> </HTML> </xsl:template> <xsl:template match="PLANET"> <TR> <TD><xsl:value-of select="NAME"/></TD> <TD><xsl:apply-templates select="MASS"/></TD> <TD><xsl:apply-templates select="RADIUS"/></TD> <TD><xsl:apply-templates select="DAY"/></TD> </TR> </xsl:template> <xsl:template match="MASS"> <xsl:value-of select="."/> <xsl:value-of select="@UNITS"/> </xsl:template> <xsl:template match="RADIUS"> <xsl:value-of select="."/> <xsl:value-of select="@UNITS"/> </xsl:template> <xsl:template match="DAY"> <xsl:value-of select="."/> <xsl:value-of select="@UNITS"/> </xsl:template> </xsl:stylesheet>
You can see the results in Figure 3.1. As you see, youve now recovered the string value of the UNITS attribute and displayed it.
Figure 3.1. Displaying attribute values, first attempt.
Figure 3.1 isnt quite perfect, howevernote that there is no space between each value in the table and the associated unit of measure. The XSLT processor simply placed the text in the result tree without any whitespace between text nodes. Although this is exactly what the XSLT recommendation requires, you want table entries such as 1516 miles, not 1516miles. How can you get that extra space?