Creating Data-Driven Stylesheets


You want to generate HTML that is styled based on data content.


XSLT attribute sets provide a nice vehicle for encapsulating the complexity of data-driven stylization. Consider how XML describes an investment portfolio:


You should display this portfolio in a table with a column showing the gain in black or the loss in red:

<xsl:stylesheet version="1.0" xmlns:xsl=""> <xsl:output method="html"/> <xsl:attribute-set name="gain-loss-font"> <xsl:attribute name="color"> <xsl:choose> <xsl:when test="(current - paid) * qty >= 0">black</xsl:when> <xsl:otherwise>red</xsl:otherwise> </xsl:choose> </xsl:attribute> </xsl:attribute-set> <xsl:template match="portfolio"> <html> <head> <title>My Portfolio</title> </head> <body bgcolor="#FFFFFF" text="#000000"> <h1>Portfolio</h1> <table border="1" cellpadding="2"> <tbody> <tr> <th>Symbol</th> <th>Current</th> <th>Paid</th> <th>Qty</th> <th>Gain/Loss</th> </tr> <xsl:apply-templates/> </tbody> </table> </body> </html> ...

Get XSLT Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.