XML technologies / XSLT / XSLT Cookbook / Extending and embedding XSLT / Native extensions of Saxon and Xalan: usage
(Excerpt from “XSLT Kochbuch” by Sal Mangano)
Problem
You want to use some useful extensions provided by these widespread XSLT implementations.
Solution
XSLT 1.0
This recipe comprises smaller recipes demonstrating the main Saxon and Xalan extensions. In every example, namespace prefix saxon is associated with "http://icl.com/saxon", and namespace prefix xalan with "http://xml.apache.org/xslt".
Outputting more than one destination file
We have already used Saxon’s ability to output multiple files several times. Saxon uses element saxon:output. It also provides element xsl:document, but this works only when the stylesheet’s version attribute is 1.1, so it is not preferred here. Attribute href specifies the output destination and can also be an attribute value template:
<saxon:output href="toc.html">
<html>
<head><title>Table of Contents</title></head>
<body>
<xsl:apply-templates mode="toc" select="*"/>
</body>
</html>
</saxon:output>Xalan takes a different approach to multiple destination files, using three instructions rather than one: redirect:open, redirect:close and redirect:write. Their extension namespace is xmlns:redirect="org.apache. xalan.xslt.extensions.Redirect". Usually redirect:write suffices: it opens, writes and closes the file itself.
Each element has a file attribute and/or a select attribute specifying the output file. The file attribute is a string, allowing a filename to be given directly. Attribute select can also contain an XPath expression, generating a filename dynamically. If both attributes exist, extension redirect first evaluates attribute select. If it yields no valid filename, it evaluates attribute file:
<xalan:write file="toc.html">
<html>
<head><title>Table of Contents</title></head>
<body>
<xsl:apply-templates mode="toc" select="*"/>
</body>
</html>
</xalan:write>Xalan’s advanced facilities let you switch from an open main output file to secondary files while leaving the main file open. This undermines XSLT’s freedom from side effects, but hopefully Xalan makes the operation predictable:
<xsl:template match="doc">
<xalan:open file="regular.xml"/>
<xsl:apply-templates select="*"/>
<xalan:close file="regular.xml"/>
<xsl:template/>
<xsl:template match="regular">
<xalan:write file="regular.xml">
<xsl:copy-of select="."/>
</xalan:write/>
</xsl:template>
<xsl:template match="*">
<xsl:variable name="file" select="concat(local-name( ),'.xml')"/>
<xalan:write select="$file">
<xsl:copy-of select="."/>
</xalan:write/>
</xsl:template>XSLT 2.0 directly supports multiple result destinations through a new element named xsl:result-document:
<xsl:result-document format="html" href="toc.html">
<html>
<head><title>Table of Contents</title></head>
<body>
<xsl:apply-templates mode="toc" select="*"/>
</body>
</html>
</xsl:result-document>Splitting a complex transformation into a pipeline of smaller transformations
Unix developers know processing pipelines, where one command’s output becomes another’s input. Other systems, including Windows, offer them too. The beauty of the pipeline approach is assembling complex tasks from simpler commands.
Since XSLT transforms one tree into another, pipelining is natural: one result tree becomes the next input. Many examples used node-set extension functions to create intermediate results for later processing. Saxon alternatively offers this through extension attribute saxon:next-in-chain of xsl:output. Attribute saxon:next-in-chain forwards output to another stylesheet whose URL is its value. Output must be pure XML; format-control attributes such as method, cdata-section-elements and so on have no effect. The second stylesheet’s result goes where the first would have sent its output without a saxon:next-in-chain attribute.
Xalan instead uses a pipeDocument extension element. The beauty of pipeDocument is that an otherwise empty stylesheet can connect independent stylesheets unaware of the pipeline. This resembles Unix pipes more closely, since the pipeline is not hard-coded into its participants. Suppose stylesheet strip.xslt removes certain elements from a book XML document, while stylesheet contents.xslt builds a table of contents from the markup hierarchy. Connect them as follows:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:pipe="xalan://PipeDocument" extension-element-prefixes="pipe">
<xsl:param name="source"/>
<xsl:param name="target"/>
<!-- Eine Liste zu erhaltender Elemente. Alle anderen werden entfernt. -->
<xsl:param name="preserve-elems"/>
<pipe:pipeDocument source="{$source}" target="{$target}">
<stylesheet href="strip.xslt">
<param name="preserve-elems" value="{$preserve-elems}"/>
</stylesheet>
<stylesheet href="contents.xslt"/>
</pipe:pipeDocument>
</xsl:stylesheet>This creates a table of contents from the specified elements without impairing independent use of strip.xsl or contents.xsl.
Working with dates and times
In Dates and times we saw many date/time recipes, but pure XSLT could not obtain the current date and time. Saxon and Xalan implement core functions from EXSLT’s dates-and-times module. This section reproduces the corresponding EXSLT documentation as a quick overview. The table lists return types followed by function names and arguments; a question mark (?) denotes optional arguments.
Table: EXSLT date and time functions.
Function | Behavior |
| Function |
| Function |
| Function |
| Function |
| Function |
| Function |
| Function |
| Function |
| Function |
| Function |
| Function |
| Function |
| Function |
| Function |
| Function |
| Function |
| Function |
| Function |
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:date="http://exslt.org/dates-and-times">
<xsl:output method="html" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
<html>
<head><title>My Dull Home Page</title></head>
<body>
<h1>My Dull Homepage</h1>
<div>It's <xsl:value-of select="date:time( )"/> on <xsl:value-of select="date:date()"/> and this page is as dull as it was yesterday.</div>
</body>
</html>
</xsl:template>
</xsl:stylesheet>XSLT 2.0 has built-in date/time support described in Dates and times, making these extensions unnecessary.
A more efficient implementation of set operations
Querying XML examined set operations other than union, directly supported by XPath’s union operator (|). Those solutions were not necessarily the most efficient or clearest.
Saxon and Xalan address this by implementing the set operations defined in EXSLT’s set module (see table).
Table: EXSLT set operations.
Function | Behavior |
| Function |
| Function |
| Function |
| Function |
| Function |
| Function |
set:distinct conveniently removes duplicates when node equality means equal string values:
<xsl:varaible name="firstNames" select="set:destinct(person/firstname)"/>set:leading and set:trailing extract nodes bracketed by others. For example, recipe Generating XSLT from XSLT used a complex expression to find the xslx:elsif and xslx:else nodes belonging to your improved xslx:if. Extensions simplify this:
<xsl:apply-templates select="set:leading(following-sibling::xslx:else | following-sibling::xslx:elsif, following-sibling::xslx:if)"/>This selects all sibling nodes of xslx:else and xslx:elseif after the current node but before the next xslx:if.
Getting more information about a source-tree node
Xalan provides functions for source-node locations. Saxon 6.5.2 provides only saxon:systemId and saxon:lineNumber. These can help debugging. To use them, set attribute TransformerFactory source_location to true using command-line switch -L or method TransformerFactory.setAttribute( ).
systemId( )systemId(node-set)Returns the system ID of the current node or first node in the node-set respectively.
lineNumber( )lineNumber(node-set)Returns the source line number of the current node or first node in the node-set respectively. Returns
-1if unknown, for example for a DOM document.columnNumber( )columnNumber(node-set)Returns the source column number of the current node or first node in the node-set respectively. Returns
-1if unknown, for example for a DOM document:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xalan="http://xml.apache.org/xslt" xmlns:info="xalan://org.apache.xalan.lib.NodeInfo">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="foo">
<xsl:comment>Matched a foo on line <xsl:value-of select="info:lineNumber( )"/> and column <xsl:value-of select="info:columnNumber( )"/>.</xsl:comment>
<!-- ... -->
</xsl:template>
</xsl:stylesheet>Interacting with a relational database
A relational database interface opens many possibilities for XSLT. Saxon and Xalan both offer SQL extensions. Stylesheets modifying database content violate XSLT’s rule of having no side effects.
Caution!
Michael Kay describes Saxon’s SQL extensions as not necessarily production-quality software, given their many design restrictions, but rather an example of using extension elements to enhance the processor’s capabilities.
Saxon provides database access through five extension elements: sql:connect, sql:query, sql:insert, sql:column and sql:close. Anyone familiar with relational databases through ODBC or JDBC should find them straightforward.
<sql:connect driver="jdbc-driver" database="DB-Name" user="Benutzername" password="Benutzerpasswort"/>Creates a database connection. All attributes can be attribute value templates. Attribute
drivernames the JDBC driver class; attributedatabasemust name something JDBC can associate with an existing database.<sql:query table="die Tabelle" column="Spaltennamen" where="Where-Klausel" row-tag="Zeilenelementname" column-tag="Spaltenelementname" disable-output-escaping="yes bzw. no"/>Executes a query and writes results into the output tree, representing rows and columns as elements named by
row-tagandcol-tagrespectively. Attributecolumncan list columns or use*for all columns.<sql:insert table="Tabellenname">Executes an SQL INSERT. Child elements (
sql:column) specify data to add to the table.<sql:column name="Spaltenname" select="XPath-Ausdruck"/>Used as a child of
sql:insert. Its value comes from attributeselector evaluation of children ofsql:column. In either case only string values work: there is no way to use other standard SQL datatypes.
Xalan’s SQL support is broader than Saxon’s, but this chapter covers only the basics. See “See also” for details. Unlike Saxon, Xalan accesses databases through extension functions.
sql:new(driver, db, user, password)Establishes a connection.
sql:new(nodelist)Establishes a connection using XML information embedded in the input document or stylesheet. Example:
<DBINFO>
<dbdriver>org.enhydra.instantdb.jdbc.idbDriver</dbdriver>
<dburl>jdbc:idb:../../instantdb/sample.prp</dburl>
<user>jbloe</user>
<password>geron07moe</password>
</DBINFO>
<xsl:param name="cinfo" select="//DBINFO"/>
<xsl:variable name="db" select="sql:new($cinfo)"/>sql:query(xconObj, sql-query)Queries the database. The
xconObjis returned bynew( ). The result is a row-set node usable as a stream. Process it row by row, reusing the same row element. Transformation can begin before the entire result arrives.sql:pquery(xconObj, sql-query-with-params)sql:addParameter(xconObj, paramValue)sql:addParameterFromElement(xconObj, element)sql:addParameterFromElement(xconObj, node-list)clearParameters(xconObj)Used together to implement parameterized queries. Parameters are
?characters embedded in the query. The variousaddParameter( )functions assign values before query execution. After aclearParameters( ), the connection object forgets all previous values.sql:close(xconObj)Closes the database connection.
Extension functions sql:query( ) and sql:pquery( ) return a document node containing, as required, an array of column-header elements, one reusable row element, and an array of col elements. Each column header (one per column) contains an attribute (ColumnAttribute) for every column descriptor in the ResultSetMetaData object. All col elements contain a text node representing that column’s value in the current row.
For more on XSLT database access, see Doug Tidwell’s book XSLT (O’Reilly, 2001).
Dynamically evaluating an XPath expression created at runtime
Saxon and Xalan both provide a powerful extension function named evaluate, evaluating a supplied string as XPath. EXSLT.org also defines dyn:evaluate( ) for better portability. XSLT 2.0 considered such a feature, but its working group chose not to pursue it: dynamic evaluation significantly affects processor runtime architecture and opportunities for static optimization.
Dynamic features help create table-driven stylesheets. This stylesheet tabulates personal information and can support almost unlimited XML formats simply by changing table entries:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:saxon="http://icl.com/saxon" xmlns:paths="http://www.ora.com/XSLTCookbook/NS/paths" exclude-result-prefixes="paths">
<xsl:output method="html"/>
<!-- Dieser Parameter gibt ein Dokument mit einer Tabelle an, die beschreibt, wie man Informationen über Leute findet. -->
<xsl:param name="pathsDoc"/>
<xsl:template match="/">
<html>
<head>
<title>People</title>
</head>
<body>
<!-- Wir laden einen Xpath-Ausdruck aus einer Tabelle [Symbol_Wingdings_224] in einem externen Dokument. -->
<xsl:variable name="peoplePath" select="document($pathsDoc)/*/paths:path[@type='people']/@xpath"/>
<table>
<tbody>
<tr>
<th>First</th>
<th>Last</th>
</tr>
<!-- Werte dynamisch den XPath aus, der Informationen über alle Personen findet. -->
<xsl:for-each select="saxon:evaluate($peoplePath)">
<xsl:call-template name="process-person"/>
</xsl:for-each>
</tbody>
</table>
</body>
</html>
</xsl:template>
<xsl:template name="process-person">
<xsl:variable name="firstnamePath" select="document($pathsDoc)/*/paths:path[@type='first']/@xpath"/>
<xsl:variable name="lastnamePath" select="document($pathsDoc)/*/paths:path[@type='last']/@xpath"/>
<tr>
<!-- Werte dynamisch den Xpath aus, der die personenspezifischen Angaben findet, die wir verarbeiten möchten. -->
<td><xsl:value-of select="saxon:evaluate($firstnamePath)"/></td>
<td><xsl:value-of select="saxon:evaluate($lastnamePath)"/></td>
</tr>
</xsl:template>
</xsl:stylesheet>Use this table for personal data encoded as elements:
<paths:paths
xmlns:paths="http://www.ora.com/XSLTCookbook/NS/paths">
<paths:path type="people" xpath="people/person"/>
<paths:path type="first" xpath="first"/>
<paths:path type="last" xpath="last"/>
</paths:paths>Add this table for personal data encoded as attributes:
<paths:paths xmlns:paths="http://www.ora.com/XSLTCookbook/NS/paths">
<paths:path type="people" xpath="people/person"/>
<paths:path type="first" xpath="@first"/>
<paths:path type="last" xpath="@last"/>
</paths:paths>Changing a variable’s value
Most XSLT books present immutable variable and parameter bindings as a feature, not a flaw. This avoids a category of bugs, clarifies stylesheets and permits performance optimizations. Sometimes immutability is simply inconvenient. Saxon provides extension element saxon:assign to bypass this restriction. However, saxon:assign works only on variables marked assignable with extension attribute saxon:assignable="yes":
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:saxon="http://icl.com/saxon" extension-element-prefixes="saxon">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:variable name="countFoo" select="0" saxon:assignable="yes"/>
<xsl:template name="foo">
<saxon:assign name="countFoo" select="$countFoo + 1"/>
<xsl:comment>This is invocation number <xsl:value-of select="$countFoo"/> of template foo.</xsl:comment>
</xsl:template>
<!- ... -->
</xsl:stylesheet>Writing first-class extension functions in XSLT 1.0
Many examples implement named templates ( named templates) invoked with xsl:call-template. This is often cumbersome when real functions callable like native XPath functions would be preferable. XSLT 2.0 permits that; in 1.0, consider EXSLT extension func:function, implemented by Saxon and current Xalan (2.3.2). The following reimplements a template from Finding substrings from the end of a string as a function:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:func="http://exslt.org/functions" xmlns:str="http://www.ora.com/XSLTCookbook/namespaces/strings" extension-element-prefixes="func">
<xsl:template match="/">
<xsl:value-of select="str:substring-before-last('123456789a123456789a123','123')" />
</xsl:template>
<func:function name="str:substring-before-last">
<xsl:param name="input"/>
<xsl:param name="substr"/>
<func:result>
<xsl:if test="$substr and contains($input, $substr)">
<xsl:variable name="temp" select="substring-after($input, $substr)" />
<xsl:value-of select="substring-before($input, $substr)" />
<xsl:if test="contains($temp, $substr)">
<xsl:value-of select="concat($substr,str:substring-before-last($temp, $substr))"/>
</xsl:if>
</xsl:if>
</func:result>
</func:function>
</xsl:stylesheet>XSLT 2.0
Most Saxon 6 extensions remain in Saxon 8, but some, such as saxon:function( ), are unnecessary in XSLT 2.0. Others extend XQuery with facilities already in XSLT. For example, saxon:index( ) and saxon:find( ) resemble XSLT’s key functionality (xsl:key and key( )). Saxon 8 also has extra features absent from earlier versions.
Getting an XPath expression for the current node
Function saxon:path( ) takes no arguments and returns a string containing an XPath expression for the context node. This resembles the XSLT debugging solution introduced in recipe Tracing stylesheet flow through its input document.
Handling and catching runtime errors
Many modern languages, such as Java and C++, provide a Try-throw-catch mechanism for runtime errors. Saxon’s commercial version (Saxon-SA) provides a saxon:try pseudo-function with similar but more limited capabilities. saxon:try evaluates its first argument as an expression. If a runtime error occurs, such as division by zero or a type error, it returns the second argument’s value:
<xsl:template match="/">
<test>
<xsl:value-of select="saxon:try(*[0], 'Index out of bounds')"/>
</test>
</xsl:template>The second argument may be an error string as here, or a default value. Michael Kay calls saxon:try a pseudo-function because, unlike normal XPath functions, it evaluates its second argument only if the first fails.
Discussion
Vendor extensions have advantages and disadvantages. They can make XSLT solutions faster or simpler than standard XSLT, sometimes enabling otherwise impossible tasks. But they can tie you to an implementation with an uncertain future.
EXSLT.org encourages vendors to follow shared conventions for popular extensions. Prefer an EXSLT solution over a vendor-specific one whenever possible.
Another approach avoids vendor implementations by writing your own, retaining full source control and allowing ports to multiple processors. Such extensions are covered in recipes Saxon extension elements, Xalan-Java 2 extension functions and Java extension function with a class-format namespace.
See also
This book does not cover every Saxon and Xalan extension. More on Saxon extensions is available at SAXON Extensions and Saxonica Documentation (XSLT 2.0). For Xalan extensions, see Xalan Extensions library.
Copyright © 2006 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “XSLT Kochbuch” is subject to the same conditions as the bound edition. The work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O'Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de