GIST logo

From Atom to XHTML using XSLT

XML Stylesheet Language Transformations (XSLT) are algorithms for converting XML documents either into other XML documents or into documents in other text formats. The notation in which these algorithms are expressed is also XML. The syntax to be used for them is specified in the World Wide Web Consortium recommendation “XSL transformations (XSLT),” which includes, in its appendix D, several examples of how to use the notation effectively.

An XSLT program is called a “stylesheet” or “transform” and is written as a single large XML element (with the tag xml:stylesheet). The stylesheet contains one or more “templates.” The program basically parses the source document and traverses its syntax tree, looking for opportunities to apply its templates; when it finds such an opportunity, it evaluates the expressions contained in the template and adds whatever those expressions generate to the output.

A template typically contains an XPath, or a segment of an XPath, and can be applied to a node in the syntax tree when the XPath matches that node. Here's a simple XSLT template:

<xsl:template match="document">
  Title: <xsl:value-of select="title"/>
  <xsl:apply-templates/>
</xsl:template>

The XPath that is to be matched is specified as an attribute of the xsl:template element. The label Title: is taken as a literal and copied to the output. The xsl:value-of element is a processing instruction; the idea is to select any title elements that are immediate constituents of the matched document element and output the text contained in those title elements.

Initially, any relative XPath specifications in the match attribute of a template are understood with reference to the root of the syntax tree. However, the example above illustrates another possibility: xsl:apply-templates is a processing instruction that causes the entire stylesheet to be applied recursively to each of the subtrees under a matched node.

By default, an XSLT stylesheet outputs all of the text contained in all nodes of the given document -- that is, the text between the starting and ending tags for any non-empty element. But it is possible to prevent this behavior by supplying a template that matches with the XPath text function and supplying no processing instructions:

<xsl:template match="text()"/>

The file /home/stone/courses/internships/syndication/examples/feed-to-xhtml.xslt contains a longer example of the constructive use of XSLT.