Next / Previous / Contents

2.2. The code

The following is the appropriate front matter for an XSLT stylesheet of this kind. Since the output method is "text", the output need not conform to any particular syntax, and so the "code" that we process here can be in any programming language, or can be any other kind of text at all.

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text"/>

Now we define a template that will find and process all the code sections in the input; that is, all the <programlisting> elements that have a role attribute "executable". The template starts at the root of the source tree and descends it, processing code sections everywhere and (implicitly) deleting all other parts. The "//" is shorthand for "descendant-or-self::".

  <xsl:template match="/">
    <xsl:apply-templates select="//programlisting[@role='executable']"/>
  </xsl:template>

The following template is the part that processes those <programlisting> elements to extract the code fragments. Notice that we do not need to repeat the "[@role='executable']" test here; the previous template will invoke this one only for the elements for which that test is true. In effect, the match="programlisting" just labels the current template as the one to be invoked by the xsl:apply-templates (above) for any <programlisting> element that it processes.

  <xsl:template match="programlisting">
    <xsl:apply-templates select="text()"/>
  </xsl:template>

Notice that we select only the text part of the code fragments. This deletes (for example) links and anchors: the author of the code document can insert these freely to create cross-reference links among parts of the code, the text of the document, and external documents. It also deletes any DocBook annotations, such as lineannotations and callouts, that may be present; again, the author can insert these anywhere they might be useful for explanation of the code.

And this is the end of the stylesheet, so we close with the appropriate tag.

</xsl:stylesheet>

Ten code lines. That's all we need!