This example illustrates the data-driven model of XSLT processing. With the data-driven model, you can create isolated templates for the types of nodes you expect to see in the output, without too much consideration of their structure. In places where the structure is locally known, you can use <xsl:for-each>
and <xsl:value-of>
to populate the template. For example, <list>
and <item>
elements appear in a regular and predictable structure. The capacity to switch smoothly between data-driven and template-driven transformation is an important feature of XSLT.
XML File (pole.xml)
<?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="poleeasy.xsl"?> <document> <title>To the Pole and Back</title> <section> <title>The First Day</title> <p>It was the <emph>best</emph> of days, it was the <emph>worst</emph> of days.</p> <list> <item><emph>best</emph> in that the sun was out.</item> <item><emph>worst</emph> in that it was 39 degrees below zero.</item> </list> <section> <title>Lunch Menu</title> <list> <item>ice cream</item> <item>popsicles</item> </list> </section> </section> <section> <title>The Second Day</title> <p>Ditto the first day.</p> </section></document>
XSLT File (poleeasy.xsl)
<?xml version='1.0'?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <HTML> <HEAD> <TITLE><xsl:value-of select="document/title"/></TITLE> </HEAD> <BODY> <H1><xsl:value-of select="document/title"/></H1> <xsl:apply-templates select="document/section"/> </BODY> </HTML> </xsl:template> <xsl:template match="section"> <DIV> <H2><xsl:value-of select="title"/></H2> <xsl:apply-templates /> </DIV> </xsl:template> <xsl:template match="p"> <P><xsl:apply-templates /></P> </xsl:template> <xsl:template match="list"> <UL> <xsl:for-each select="item"> <LI><xsl:apply-templates /></LI> </xsl:for-each> </UL> </xsl:template> <xsl:template match="emph"> <I><xsl:apply-templates /></I> </xsl:template> <xsl:template match="text()"> <xsl:value-of select="."/> </xsl:template> <xsl:template match="title"/> </xsl:stylesheet>
Formatted Output
Processor Output
The white space has been adjusted for clarity.
<HTML> <HEAD> <TITLE>To the Pole and Back</TITLE> </HEAD> <BODY> <H1>To the Pole and Back</H1> <DIV> <H2>The First Day</H2> <P>It was the <I>best</I> of days, it was the <I>worst</I> of days.</P> <UL> <LI><I>best</I> in that the sun was out.</LI> <LI><I>worst</I> in that it was 39 degrees below zero.</LI> </UL> <DIV> <H2>Lunch Menu</H2> <UL> <LI>ice cream</LI> <LI>popsicles</LI> </UL> </DIV> </DIV> <DIV> <H2>The Second Day</H2> <P>Ditto the first day.</P> </DIV> </BODY> </HTML>