XML technologies / XML / Python & XML / Transforming XML with XSLT / XSLT elements

(Excerpt from “Python & XML” by Christopher A. Jones & Fred L. Drake, Jr.)

Much XSLT functionality takes the form of elements performing particular tasks. The entire language is XML-based, and several books describe its features. This section introduces elements and fundamentals so you can begin using it in daily work.

The stylesheet element

The xsl:stylesheet element is always the root of standalone stylesheets and is also used in embedded stylesheets. The stylesheet element has required and optional attributes giving the XSLT processor further stylesheet details. A second root element in the namespace of XSLT is named xsl:transform. It is identical to xsl:stylesheet except in name, and can replace xsl:stylesheet without changing meaning.

The id attribute is optional, but useful when the stylesheet belongs to a larger XML document, as with embedded stylesheets. XML requires every ID-typed attribute—not necessarily named id but declared in the DTD with data type ID—be unique within its document. IDs are powerful when dynamically generating multiple stylesheets in a larger compound document.

The attribute version is required because it identifies the XSLT version. Every xsl:stylesheet element must have a version attribute. Simplified stylesheet roots also need a version attribute explicitly associated with the XSLT namespace, as in ships-template.html.

Namespace prefixes are strongly recommended for stylesheet elements, distinguishing them from output elements or other elements in a containing document. The namespace URI must be the W3C URI "http://www.w3.org/1999/XSL/Transform".

A typical stylesheet element begins like this:

 <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 

This specifies namespace and version, but has no id attribute.

XSLT can generate XML, HTML or other formats, so specify the intended output using the element xsl:output, requiring one attribute:

 <xsl:output method="xml"/> 

The attribute method can have values xml, html or text, meaning roughly what you expect. For XHTML output use xml. For non-XML, non-HTML formats, text controls every output byte, intended mainly for text formats. For RTF or TeX-based languages, text is the right choice. Other formats can often be produced by generating an XSL-FO document and using a processor familiar with target-format details. Python products can also generate binary formats such as PDF from XML without stylesheets or XSL-FO; see ReportLab - Content to PDF Solutions —translator’s note.

Without an xsl:output element, or without its method attribute, output is XML.

Creating a template element

The element xsl:template performs much transformation work. This XSLT instruction normally specifies a matching pattern or a name for calls from elsewhere in the stylesheet. The body of xsl:template supplies output markup whenever the processor calls or matches the template.

Optional attributes define its name (name) and matching rule (match), plus mode (mode) and priority (priority). The mode specifies a namespace prefix considered when the instruction xsl:apply-templates, explained next, uses a particular mode. The priority attribute resolves conflicts between templates matching the same pattern: if the processor can choose, it uses priority if specified.

The most important attribute is match. The match attribute contains an XPath expression identifying target elements. Instead of parsing the earlier address example with SAX and waiting for events, this match attribute and XPath syntax locate the first address line:

 <xsl:template match="/addr-record/address1"> 

This starts at the root element addr-record and selects its child address1. Use the same expression in the select attribute to display it, as shown later.

Earlier templates matched the whole XML document and produced complete HTML. They can also match individual input elements:

<xsl:template match="/addr-record/address1">
  <html>
    <head>       
      <title>Transformierter Satz von Adressen</title>
    </head>
    <body>
      <p>Wir haben /addr-record/address1 verwendet</p>
      <p><xsl:value-of select="/addr-record/address1"/></p>
    </body>
  </html>
</xsl:template>

Here an element address1, child of the root addr-record, matches before rules and content are processed. The processor instantiates the template, outputs its HTML children and processes further XSLT elements. Running this modified stylesheet produces the expected HTML followed by remaining XML text: without rules for that text, it is simply emitted. The element xsl:apply-templates lets rules nest, supporting deeply nested documents with the intended transformation.

Applying templates

For nested document structures, the element apply-templates recursively applies rules throughout the document. Formatted text illustrates nesting: paragraphs with bold or multicolored sentences, code examples and other formatting structures inside one another.

File systems are another example: directories contain arbitrary numbers of files and subdirectories, each recursively obeying the same rule. The tree can become complex.

Nested XML often needs rules for particular tags while allowing those tags and rules to nest. Use apply-templates elements. Consider this XML:

<deep-nest>        
        <title>Sample Text</title>
        <big>T</big>his is an example of
        <red>Fancy Text</red> that comes in
        <blue>m<big>u</big></blue><green>l<big>
        t</big></green><blue>i<big>p</big>
        </blue><green>l<big>e</big></green>
        colors. Many of <bold>these</bold>
        elements are <big><green>N</green>
        <blue>E</blue><green>S</green><blue>T</blue>
        <green>E</green><blue>D</blue></big> within
        each other.
</deep-nest>

These elements contain other elements without a fixed order, since no DTD defines one. Accommodate the nesting with the instruction xsl:apply-templates. The element big may occur in a color, a bold or a title element. Its template element is therefore:

<xsl:template match="big">
      <font size="5"><xsl:apply-templates/></font>
</xsl:template>

Wherever a big element occurs, it becomes a font tag. Its entire big content is also matched against other templates because the instruction xsl:apply-templates is present. Here is the complete stylesheet:

<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html"/>
  <xsl:template match="deep-nest">
    <html><body><xsl:apply-templates/></body></html>
  </xsl:template>
  <xsl:template match="title">
    <h1><xsl:apply-templates/></h1>
  </xsl:template>
  <xsl:template match="big">
    <font size="5"><xsl:apply-templates/></font>
  </xsl:template>
  <xsl:template match="red">
    <font size="3" color="#FF0000"><u><xsl:apply-templates/></u></font>
  </xsl:template>
  <xsl:template match="blue">
    <font color="#0000FF"><xsl:apply-templates/></font>
  </xsl:template>
  <xsl:template match="green">
    <font color="#00FF00"><b><xsl:apply-templates/></b></font>
  </xsl:template>
  <xsl:template match="bold">
    <b><i><xsl:apply-templates/></i></b>
  </xsl:template>
</xsl:stylesheet>

This stylesheet’s most important property is its well-formedness. Each source element is accounted for and processed as desired by placing xsl:apply-templates inside it. Passing XML and the stylesheet to the processor yields:

<html>
  <body>
    <h1>Sample Text</h1>
    <font size='5'>T</font>his is an example of
    <font color='#FF0000' size='3'>
      <u>Fancy Text</u>
    </font> that comes in
    <font color='#0000FF'>m<font size='5'>u</font>
    </font>
    <font color='#00FF00'>
      <b>l<font size='5'>
        t</font></b>
    </font>
    <font color='#0000FF'>i<font size='5'>p</font>
    </font>
    <font color='#00FF00'>
      <b>l<font size='5'>e</font></b>
    </font>
    colors. Many of <b><i>these</i></b>
    elements are <font size='5'>
      <font color='#00FF00'>
        <b>N</b>
      </font>
      <font color='#0000FF'>E</font>
      <font color='#00FF00'>
        <b>S</b>
      </font>
      <font color='#0000FF'>T</font>
      <font color='#00FF00'>
        <b>E</b>
      </font>
      <font color='#0000FF'>D</font>
    </font> within
    each other.
  </body>
</html>

Accessing a node’s value

The element xsl:value-of generates output from an expression. Its possible attributes are select and disable-output-escaping. The select attribute is required, generating replacement content. The select attribute takes an XPath expression. Given XML <a><b><c id="c">content</c></b></a>, this expression produces the word “content”.

 <xsl:value-of select="/a/b/c"/> 

To retrieve an attribute, use the symbol @ in the select attribute:

 <xsl:value-of select="/a/b/c/@id"/> 

The attribute disable-output-escaping prevents escaping characters that might be mistaken for markup. This can help with text output. Consider the document:

 <doc>A &amp; B</doc> 

and this template:

<xsl:template match="doc">
    <xsl:value-of select="text( )" disable-output-escaping="yes"/>
</xsl:template>

If disable-output-escaping retained its default value no, the template result would appear as A &amp; B, but with the attribute set to yes it appears as A & B. This is unnecessary if the xsl:output element sets output to text.

We have used the element xsl:value-of earlier because it is central to XSLT.

Iterating over elements

The element xsl:for-each iterates over particular element types within a matched template. Its required select attribute identifies nodes to iterate. The select attribute can return any collection of elements or nodes, from a simple name or a path expression.

The xsl:for-each element helps transform only selected elements of mixed content. This XML purchase document includes several purchase types:

<?xml version="1.0"?>
<purchases>
     <product name="Floppy-Disk" price="3.50"/>
     <service name="Web-Aktualisierungen" price="6.95"/>
     <product name="Ink-Jet-Patrone" price="19.95"/>
     <service name="Consulting" price="150h"/>
</purchases>

For products rather than services, use the for-each element to select only product elements:

<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html"/>
  <xsl:template match="/">
    <html><body><xsl:apply-templates/></body></html>
  </xsl:template>
  <xsl:template match="purchases">
    <xsl:for-each select="product">
      <p>Produkt: <xsl:value-of select="./@name"/> Preis: <xsl:value-of select="./@price"/></p>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

The stylesheet generates HTML with product details but no service details.

XSLT is a substantial language beyond this book. Besides selection, searching and iteration, it provides control structures, conditions, variables and functions. Many learning resources exist; a good introduction is well worth your time if you plan to use XSLT.

  

 

 

 

back to top