Using XML and XSLT to Personalize a Web Site Part 2: XSL Transformation Stylesheet BasicsCreating XHTML from XML
Selecting Data to Transform
In the previous section, we saw one template that matched, or selected, the entire document by using match="/". The / represents the document root, or the highest level of the tree. Although it does allow us to get the content on the page, it's not tremendously helpful in helping us format it. We have several different types of content, and they all need individual treatment.
To do that, we're going to create several different templates, and use the match attribute to determine the content to which they apply:
<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <xsl:apply-templates /> </xsl:template> <xsl:template match="content/blurb"> <p>Blurb:</p> <xsl:value-of select="." /> </xsl:template> <xsl:template match="content/gossip"> <p>Gossip:</p> <xsl:value-of select="." /> </xsl:template> <xsl:template match="content/admin"> <p>Admin:</p> <xsl:value-of select="." /> </xsl:template> </xsl:stylesheet>
Notice that we've changed the xsl:value-of element in the original template to an xsl:apply-templates element. This xsl:apply-templates element tells the processor that it should take all the children of the current node or context node, and see whether there are any templates that apply to them.
In this case, there are three more templates. Each one uses the match attribute to tell the processor which parts of the original XML document to transform via an XPath expression. XPath is basically a way to identify parts of an XML document by way of the parent-child relationships. The blurb element is a child of the content element, so it's indicated as content/blurb.
If you're using the working draft namespace, you'll need to add two more templates at the top of the file:
<xsl:template match="*"> <xsl:apply-templates /> </xsl:template> <xsl:template match="text()"> <xsl:value-of select="." /> </xsl:template>
The recommendation implementation includes these templates as built-in templates.
Now if we access the XML file, it will look like Figure 5.
Figure 5 A style sheet can designate specific content to output.