April 03, 2003

Advanced XSLT usage or using XSLT to generate XSLT

XSLT
Lake Tahoe from Heavenly

XSLT is a very powerful language. Most people use it to convert XML to HTML: they have an XML document which needs to be translated to a rich HTML document.

The simplest way to do this is to identify how the input XML document maps to the final HTML page, and come up with the XSLT stylesheet that embeds in its templates the HTML elements of the end result. While this works fine for one HTML page, it becomes really tedious if the page needs to change often or if you need to format the input XML multiple times.

A much better approach is to take the resulting HTML page and annotate it with your own special elements. These special elements are invented for your specific problem to delimit portions of the HTML page that need to be replaced with dynamic content from the XML input file.

Once you've annotated the output file, you can write an XSLT program that takes the output page and generates an XSLT stylesheet. The generated XSLT stylesheet will take the input XML document and generate an HTML page with exactly the same structure of the page you want.

There are few things that you need to worry about when writing such an XSLT program. The output you generate is not a generic XML output, it is an XSLT program which needs to follow the XSLT namespace. To generate this namespace you need to use the xsl:namespace-alias element to alias a namespace in the current document to the XSLT namespace:

<xsl:stylesheet
  version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:gen="dummy-namespace-for-the-generated-xslt"
  exclude-result-prefixes="xsl">

  <xsl:namespace-alias stylesheet-prefix="gen" result-prefix="xsl"/>

  <xsl:template match="/">
    <!-- Generate the structure of the XSL stylesheet -->
    <gen:stylesheet version="1.0">
      <gen:output method="html"/>

      <!-- put the logic for the generated XSLT here --!>
      <gen:template match="...">
        ...
      </gen:template>
    </gen:stylesheet>
  </xsl:template>
</xsl:stylesheet>

Writing such XSLT programs is not trivial, but you'll appreciate how clean they are. You will not have to embed in your stylesheet any of the output HTML that you need to generate; the generate stylesheet will have all that.

Posted by ovidiu at April 03, 2003 09:24 PM |
 
Copyright © 2002-2016 Ovidiu Predescu.