Share via


Data-Driven Transformations

 

Template-driven transformations are useful for processing source documents with regular and homogenous data structures. Data-driven transformations, however, are usually better for processing source documents with complex and irregular data structures. The following book review article is an example of an irregular data structure.

<?xml version='1.0'?>
<?xml-stylesheet type="text/xsl" href="book-review.xsl"?>
<book-review>
   <title>A Good Book</title> by <author>The Good Writer</author>, 
   published by <publisher>The Publisher</publisher> on <date>A Good 
   Day</date>, is indeed a good book. However, the one titled <title>
   A Bad Book</title> by the same publisher is very bad. This reviewer
   is left to wonder whether this is because <title>A Bad Book</title>
   was written by <author>A Bad Author</author>, or because it was 
   published on <date>A Bad Date</date>.
</book-review>

The elements contained in <book-review> can be arbitrary, and there is no intrinsic order of elements. The best way to display the content in this case is to follow the order in which the elements appear in the source document. To do this, you cannot set up templates to decide where different data elements appear in the output, and feed the source document into the predefined template, as you would in a template-driven transformation. In a data-driven transformation, templates are reactive — that is, they are called whenever a matching data element is encountered.

The following is an example of a data-driven XSLT style sheet for displaying the book review article above.

XSLT File (book-review.xsl)

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <HTML>
      <HEAD>
      </HEAD>
      <BODY>
         <xsl:apply-templates />
      </BODY> 
    </HTML>
  </xsl:template>

  <xsl:template match="book-review">
      <P><xsl:apply-templates /></P>
  </xsl:template>

  <xsl:template match="title">
      <SPAN style="font-weight:bold"><xsl:value-of select="."/></SPAN>
  </xsl:template>

  <xsl:template match="author">
      <SPAN style="font-style:italic"><xsl:value-of select="."/></SPAN>
  </xsl:template>
  <xsl:template match="publisher">
      <SPAN style="color:blue"><xsl:value-of select="."/></SPAN>
  </xsl:template>
  <xsl:template match="date">
      <SPAN style="font-family:courier"><xsl:value-of select="."/></SPAN>
  </xsl:template>

</xsl:stylesheet>

The following topics discuss data-driven transformations in more detail.