Listing 2-6. Namespace Handling in XSLT and XPath
<xsl:stylesheet
xmlns:xsl=http://www.w3.org/1999/XSL/Transform
version=1.0
>
<xsl:output method=html/>
<xsl:template match=/>
<html><head><title>Two Chairmens Wisdom</title></head><body>
<xsl:apply-templates />
</body></html>
</xsl:template>
<xsl:template match=*[local-name()=saying]>
<xsl:variable name=color>
<xsl:choose>
<xsl:when test=contains(namespace-uri(),red)>red</xsl:when>
<xsl:when test=contains(namespace-uri(),green)>green</xsl:when>
<xsl:otherwise>blue</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<div style={concat(color:,$color)}>
<xsl:apply-templates/>
</div>
</xsl:template>
</xsl:stylesheet>
The match attribute of that template matches all element nodes (thats what
the asterisk stands for) such that their local name is saying. As you can see, XPath
has a local-name() function and (a few lines farther down) a namespace-uri()
function. Both return strings that you can work with using XPath string functions,
such as contains(). To compute the color name, we use xsl:choose (the XSLT
equivalent of the switch statement in C and derived languages).
If all namespace URIs contained the color name right after the substring
sayings.org, we could replace the xsl:choose expression with code that extracts
the color name from the namespace URI:
<xsl:variable name=color
select=substring-after(namespace-uri(),.sayings.org.)
>
This would generate different colors from different data without any changes
in the stylesheet.
57
Well-Formed Documents and Namespaces