|
|
Listing A.8 displays the contents of the XSL stylesheet svgSalesGraph1.xsl that generates an SVG document that contains a simple bar chart based on the data in the XML data in sales.xml. For simplicity, this example does not scale the data values or display labeled axes so that you can focus on the logic for generating the bar graph.
Listing A.8 svgSalesGraph1.xsl
<?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:variable name="barWidth" select="20"/> <xsl:variable name="maxHeight" select="400"/> <xsl:template match="/"> <xsl:call-template name="graph"> <xsl:with-param name="sales" select="/sales/months/month"/> </xsl:call-template> </xsl:template> <xsl:template name="graph"> <xsl:param name="sales"/> <xsl:variable name="bar" select="0"/> <svg width="100%" height="100%"> <!-- For each sales item (i.e., month): 1) set current bar color (either red or blue) 2) invoke template to create SVG <rect> element --> <xsl:for-each select="$sales"> <xsl:variable name="revenue" select="./revenue"/> <xsl:variable name="color"> <xsl:choose> <xsl:when test="position()mod 2=0">red</xsl:when> <xsl:otherwise>blue</xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:call-template name="generateRect"> <xsl:with-param name="."/> <xsl:with-param name="xPos" select="position()*40"/> <xsl:with-param name="yPos" select="$maxHeight - $revenue"/> <xsl:with-param name="revenue" select="$revenue"/> <xsl:with-param name="color" select="$color"/> </xsl:call-template> </xsl:for-each> </svg> </xsl:template> <!-- template generates SVG <rect> element --> <xsl:template name="generateRect"> <xsl:param name="xPos"/> <xsl:param name="yPos"/> <xsl:param name="revenue"/> <xsl:param name="color"/> <rect x="{$xPos}" y="{$yPos}" width="{$barWidth}" height="{$revenue}" style="fill:{$color}"/> </xsl:template> </xsl:stylesheet>
Listing A.8 initializes a set of variables and the main logic occurs in a 'for-each' loop that sequentially processes the <month> elements contained in the file sales.xml. The revenue associated with each <month> element is passed as a parameter to the generateRect template, which generates an SVG <rect> element whose altitude equals the revenue for the current month.
After you are comfortable with the code in Listing A.8, you see how it forms the basis for the XSL stylesheet svgSalesGraph2.xsl on the CD-ROM which generates a more complete bar graph; that is, an x-axis labeled by the months of the year, a y-axis, and the revenue amount just above the top of each bar in the graph.
|
|