Introduction EXSLT extensions Xalan namespace Redirect nodeset NodeInfo extension functions SQL library PipeDocument evaluate tokenize Extensions for XSLTC Examples: Redirect, nodeset, SQL library
| Unless otherwise specified, the Xalan-Java extensions library discussed in this section refers to the Xalan-Java Interpretive processor. See Extensions for XSLTC for more information.
| Introduction |
| Extension elements and functions provide a powerful mechanism for extending and simplifying what you can do with an XLST processor like Xalan. With input and contributions from the XML open-source developer community, we are working on placing the most useful extensions in an extensions library distributed with Xalan-Java. If you have ideas and/or contributions you would like to make, please email us at the Xalan Development Mailing List.
| EXSLT extensions |
| Xalan-Java supports the EXSLT initiative to provide a set of standard extension functions and elements to XSLT users. Xalan-Java includes implementations for the following EXSLT extension modules: EXSLT common functions EXSLT math functions EXSLT set functions EXSLT date-and-time functions EXSLT dynamic functions EXSLT string functions The EXSLT func:function and func:result elements (see EXSLT - func:function) All EXSLT extensions use namespaces specified in the EXSLT specification. For example, to use the EXSLT math functions, specify a namespace URI as follows: `xmlns:math="http://exslt.org/math"` Anyone who would like to help by implementating other EXSLT extensions is more than welcome. Please email us at the Xalan Development Mailing List.
| Xalan namespace |
| The Xalan extensions are implemented in one of the classes under org.apache.xalan.lib. The main extension class is org.apache.xalan.lib.Extensions. Some extension functions (e.g. intersection, difference, etc.) used to be in this class are now moved to the corresponding EXSLT modules. All Xalan extensions use namespace URIs starting with: `http://xml.apache.org/xalan` If you are calling Xalan-Java-supplied extensions, we recommend that you define the corresponding namespace in your stylesheet, and call the extension using the namespace prefix that you have associated with that namespace. That way, if we later reorganize how the Xalan-Java-supplied extensions are stored, you won't have to modify your stylesheet. For an example that uses this namespace, see Example with the nodeset extension function.
| Redirect |
| A standard XSL transformation involves an XSL stylesheet, an XML source tree, and the transformation result tree. The transformation sends the entire result to a single javax.xml.transform.Result object. The namespace for the Redirect extension is: `http://xml.apache.org/xalan/redirect` It supplies three extension elements that you can use to redirect portions of your transformation output to multiple files: <open>, <write>, and <close>. If you use the <write> element alone, the extension opens a file, writes to it, and closes the file immediately. If you want explicit control over the opening and closing of files, use <write> in conjunction with the <open> and <close> elements. The <open> and <write> elements include a file attribute and/or a select attribute to designate the output file. The file attribute takes a string, so you can use it to directly specify the output file name. The select attribute takes an XPath expression, so you can use it to dynamically generate the output file name. If you include both attributes, the Redirect extension first evaluates the select attribute, and falls back to the file attribute if the select attribute expression does not return a valid file name. The <open> and <write> elements also support an append attribute. If the append attribute is set to true or yes, then the result is appended to the output file.
| Example with the Redirect extension |
| Suppose you are outputting the bulk of your result tree to one file, but you want to output the transformation of all <foo> elements and their children to another file. The following example illustrates the basic structure of the XML source:
    <?xml version="1.0"?>
    <doc>
      <foo file="foo.out">
        Testing Redirect extension:
          <bar>A foo subelement text node</bar>
      </foo>
      <main>
        Everything else
      </main>
    </doc>
This stylesheet redirects part of the output to a secondary file:
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        version="1.0"
        xmlns:redirect="http://xml.apache.org/xalan/redirect"
        extension-element-prefixes="redirect">

      <xsl:template match="/">
        <standard-out>
          Standard output:
          <xsl:apply-templates/>
        </standard-out>
      </xsl:template>

      <xsl:template match="main">
        <main>
          <xsl:apply-templates/>
        </main>
      </xsl:template>

      <xsl:template match="/doc/foo">
        <redirect:write select="@file">
          <foo-out>
            <xsl:apply-templates/>
          </foo-out>
        </redirect:write>
      </xsl:template>

      <xsl:template match="bar">
        <foobar-out>
          <xsl:apply-templates/>
        </foobar-out>
      </xsl:template>

    </xsl:stylesheet>
The standard output is:
    <?xml version="1.0" encoding="UTF-8"?>
    <standard-out>
      Standard output:
      <main>
        Everything else.
      </main>
    <standard-out>
The output redirected to foo.out is:
    <?xml version="1.0" encoding="UTF-8"?>
    <foo-out>
        Testing Redirect extension:
        <foobar-out>foo subelement text node</foobar-out>
      </foo-out>
For more information on using the Redirect extension to send output to multiple files, examine the SimpleRedirect sample and see the Redirect class Javadoc.
| nodeset |
| Implemented in org.apache.xalan.lib.Extensions, `nodeset (result-tree-fragment)` casts a result tree fragment into a node-set. To use the nodeset extension, you can either use the `nodeset` function in the namespace `xmlns:xalan="http://xml.apache.org"` or the EXSLT extension function `node-set` in the namespace `xmlns:common="http://exslt.org/common"`.
| When you bind a variable to a template, rather than to the value generated by a select expression, the data type of the variable is result tree fragment. For more information, see Result Tree Fragments.
| Example with the nodeset extension function |
| The following stylesheet uses the nodeset extension function to cast a result tree fragment into a node-set that can then be navigated in standard XPath manner. It uses the http://xml.apache.org/xalan namespace to provide access to the nodeset() method in xml.apache.xalan.lib.Extensions.
    <?xml version="1.0"?>
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                       version="1.0"
                       xmlns:xalan="http://xml.apache.org/xalan"
                       exclude-result-prefixes="xalan">
    <xsl:template match="/">
      <out>
    	  <xsl:variable name="rtf">
          <docelem>
            <elem1>
              <elem1a>ELEMENT1A</elem1a>
              <elem1b>,ELEMENT1B</elem1b>
            </elem1>
            <elem2>
              <elem2a>ELEMENT2A</elem2a>
            </elem2>
          </docelem>
        </xsl:variable>
          <xsl:for-each select="xalan:nodeset($rtf)/docelem//*">
            <xsl:value-of select="name(.)"/><xsl:text>,</xsl:text>
          </xsl:for-each>
      </out>
    </xsl:template>
    </xsl:stylesheet>
The output of running this stylesheet (with any XML input source) is a comma-delimited list of the element names in the node-set `<out>elem1,elem1a,elem1b,elem2,elem2a</out>`
| For illustration purposes, the preceding stylesheet pays no attention to the structure and content of the XML input document. Instead, it processes the template (in the stylesheet) bound to the variable named rtf.
| NodeInfo |
| org.apache.xalan.lib.NodeInfo provides extension elements that you can use to get information about the location of nodes in the source document: systemId publicId (to be done) lineNumber columnNumber
| If you want to use the NodeInfo extension elements, you MUST set the TransformerFactory source_location attribute to true. You can use the command-line utility -L flag or the TransformerFactory.setAttribute() method to set this attribute.
| systemId |
| Implemented in org.apache.xalan.lib.NodeInfo, `systemId()` returns the system ID for the current node, and `systemId(node-set)` returns the system ID of the first node in the node-set.
| publicId |
| To be done. Implemented in org.apache.xalan.lib.NodeInfo, `publicId()` will return the public ID for the current node, and `publicId(node-set)` will return the public ID of the first node in the node-set.
| lineNumber |
| Implemented in org.apache.xalan.lib.NodeInfo, `lineNumber()` returns the line number in the source document for the current node, and `lineNumber(node-set)` returns the line number in the source document for the first node in the node-set.
| This function returns -1 if the line number is not known (for example, the source is a DOM Document).
| columnNumber |
| Implemented in org.apache.xalan.lib.NodeInfo, `columnNumber()` returns the column number in the source document for the current node, and `columnNumber(node-set)` returns the column number in the source document for the first node in the node-set.
| This function returns -1 if the column number is not known (for example, the source is a DOM Document).
| SQL library |
| Setting up a connection Parameterized queries SQL library example SQL library sample applications The namespace for the SQL extension is: `http://xml.apache.org/xalan/sql` The SQL extension provides extension functions for connecting to a JDBC data source, executing a query, and working incrementally through a "streamable" result set. Streaming (reuse of a single row node to traverse the result set) is the default mode of operation. if you want unlimited access to the entire result set, you can cache the query result set (1 row node for each row in the result set). If you use streaming mode (the default), you can only access row elements one at a time moving forward through the result set. The use of XPath expressions in your stylesheet, for example, that attempt to return nodes from the result set in any other manner may produce unpredictable results.
| Many features of the SQL library, including support for connection pools, parameterized queries, caching, and added support for extracting connection information and query parameters from XML source documents exist thanks to John Gentilin (johnglinux@eyecatching.com), who has also added a number of SQL library samples.
4. org.apache.xalan.lib.sql.XConnection provides a number of extension functions that you can use in your stylesheet. new() -- Use one of the XConnection constructors to connect to a data source, and return an XConnection object. You can use one of the constructors creates a connection pool from which stylesheets can obtain connections to a datasource. To support connection pools, SQL library includes a ConnectionPool interface and a implementation: DefaultConnectionPool. You can also provide your own ConnectionPool implementation. query() -- Use the XConnection object query() method to return a "streamable" result set in the form of a row-set node. Work your way through the row-set one row at a time. The same row element is used over and over again, so you can begin "transforming" the row-set before the entire result set has been returned. pquery(), addParameter(), addParameterFromElement(), clearParameters() -- Use the XConnection pquery() method in conjunction with these other methods to set up and execute parameterized queries. Use enableStreamingMode() to use a single row node to "stream" through the result set, and disableStreamingMode() to cache the query result set.
   | enableStreamingMode and disableStreamingMode() are depricated See SQL Extension Features.
close() -- Use the XConnection object close() method to terminate the connection.
| SQL Extension Feature Settings |
| The SQL Extension allows features of the extension to be set through the setFeature / getFeature interface. To set a feature, use: `<xsl:value-of select=" sql:setFeature($db, 'feature-name', 'feature-value')"/>` To retrive the current value of the feature, use: `<xsl:value-of select=" sql:getFeature($db, 'feature-name')"/>`
Feature | Valid Values
streaming | true or false
The query() and pquery() extension functions return a Document node that contains (as needed) an array of column-header elements, a single row element that is used repeatedly, and an array of col elements. Each column-header element (one per column in the row-set) contains an attribute (ColumnAttribute) for each of the column descriptors in the ResultSetMetaData object. Each col element contains a text node with a textual representation of the value for that column in the current row.
| Setting up a connection |
| You can place connection information (JDBC driver, datasource URL, and usually user ID and password) in stylesheets or in XML source documents. The following stylesheet fragment uses stylesheet parameters to designate a JDBC driver and datasource. The default parameter values can be overridden with runtime parameter values.

          <xsl:param name="driver" select="'org.apache.derby.jdbc.EmbeddedDriver'"/>
          <xsl:param name="datasource" select="'jdbc:derby:sampleDB'"/>
          <xsl:param name="query" select="'SELECT * FROM import1'"/>
You can also obtain connection information from the XML source document that you use for the transformation. Suppose you have the following DBINFO nodeset in an XML document:

          <DBINFO>
          <dbdriver>org.apache.derby.jdbc.EmbeddedDriver</dbdriver>
          <dburl>jdbc:derby:sampleDB</dburl>
          <user>jbloe</user>
          <password>geron07moe</password>
          </DBINFO>
In the stylesheet, you can extract this information as follows:
         <xsl:stylesheet version 1.0
               xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
               xmlns:sql="http://xml.apache.org/xalan/sql"
               extension-element-prefixes="sql">
            <xsl:param name="cinfo" select="//DBINFO"/>
            <xsl:variable name="db" select="sql:new($cinfo)"/>
          ....
For an example of both approaches, see Basic Connection samples. You can also create a named connection pool that is maintained external to Xalan-Java.
            import org.apache.xalan.lib.sql.DefaultConnectionPool;
            import org.apache.xalan.lib.sql.XConnectionPoolManager;
            ...
            DefaultConnectionPool cp = new DefaultConnectionPool();
            cp.setDriver("org.apache.derby.jdbc.EmbeddedDriver");
            cp.setURL("jdbc:derby:sampleDB");
            cp.setUser("");
            cp.setPassword("");
            // Start with 10 connections.
            cp.setMinConnections(10);
            cp.enablePool();
            // Register the connection pool so stylesheets can use it.
            XConnectionPoolManager pm = new XConnectionPoolManager();
            pm.registerPool("extpool", cp);
A stylesheet can use this connection pool as follows:
           <xsl:stylesheet version 1.0
           xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
           xmlns:sql="http://xml.apache.org/xalan/sql"
           extension-element-prefixes="sql">
           ...
            <xsl:variable name="db" select="sql:new($driver, 'extpool')"/>
For an example, see the ExternalConnection sample.
| Parameterized queries |
| To define a parameterized query, use a SQL query string with a question mark (?) for each parameter. You can provide the parameter values at runtime with stylesheet parameters or with nodes in the XML source document. For each parameter, you should also designate the SQL data type. XConnection provides a number of addParameter() methods and an addParameterFromElement() method that you can use as extension functions to pull in the parameter values (in the order the parameters appear in the query). To execute the query and return the result set, call the pquery() method as an extension function. There are two variations of the pquery() method. The one you should ordinarily use includes as arguments the SQL query string and a string list (delimited by the space, tab, or line feeds) of parameter types. For example:
            <xsl:variable name="resultset"
            select=sql:pquery($XConnectionObj,
                              'select * from X where Y = ? and Z = ?',
                              'int string')"/>
For a complete example, see the Parameterized query sample.
| Example with SQL library |
| This example displays the result set from a table in a sample Derby database. It is also available as a sample application; see SQl Extension Samples.
          <?xml version="1.0"?>
          <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
              version="1.0"
              xmlns:sql="http://xml.apache.org/xalan/sql"
              extension-element-prefixes="sql">
          <xsl:output method="html" indent="yes"/>
          <xsl:param name="query" select="'SELECT * FROM import1'"/>
          <xsl:template match="/">
          <!-- 1. Make the connection -->
          <xsl:variable name="products"
                  select="sql:new('org.apache.derby.jdbc.EmbeddedDriver',
                 'jdbc:derby:sampleDB')"/>
          <HTML>
          <HEAD>
          </HEAD>
          <BODY>
            <TABLE border="1">
            <!--2. Execute the query -->
            <xsl:variable name="table" select='sql:query($products, $query)'/>
              <TR>
              <!-- Get column-label attribute from each column-header-->
              <xsl:for-each select="$table/sql/metadata/column-header">
                <TH><xsl:value-of select="@column-label"/></TH>
              </xsl:for-each>
              </TR>
              <xsl:apply-templates select="$table/sql/row-set/row"/>
              <xsl:text>&#10;</xsl:text>
            </TABLE>
          </BODY>
        </HTML>
        <!-- 3. Close the connection -->
        <xsl:value-of select="sql:close($products)"/>
      </xsl:template>

      <xsl:template match="row">
            <TR>
              <xsl:apply-templates select="col"/>
            </TR>
      </xsl:template>

      <xsl:template match="col">
        <TD>
          <!-- Here is the column data -->
          <xsl:value-of select="text()"/>
        </TD>
      </xsl:template>

    </xsl:stylesheet>
| pipeDocument |
| Implemented in org.apache.xalan.lib.PipeDocument, the pipeDocument extension element pipes an XML document through a series of one or more transformations. The output of each transformation is piped to the next transformation. The final transformation creates a target file. The namespace for the pipeDocument extension is: `http://xml.apache.org/xalan/PipeDocument` Suppose, for example,you have a stylesheet that is processing a "book" document with elements designating the documents to be transformed. This primary stylesheet generates a table of contents for the book. For each source document it uses a pipeDocument extension element to pipe the document through a series of one or more transformations.
| Sample: generating a table of contents and an HTML "book" |
| An XML "book" document contains a number of doc elements like the following: `<doc source="sources/intro.xml" id="intro" label="Introduction">` The source attribute identifies the document to be transformed, the id is the output file name, and the primary stylesheet places the label in the table-of-contents link. The stylesheet declares the pipeDocument namespace, designates the namespace prefix as an extension element prefix, and contains a parameter designating where the output files are to be placed:
    <xsl:stylesheet version="1.0"
       xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
       xmlns:pipe="http://xml.apache.org/xalan/PipeDocument"
       extension-element-prefixes="pipe">

    <xsl:param  name="destdir" value="html/output">
    ...
This stylesheet contains a template where each doc element is processed. For each doc element, the stylesheet adds an entry to the table-of-contents document. The extension element pipes the specified document through a series of two transformations, with an stylesheet input parameter for the first transformation. The pipeDocument target attribute designates the output from the second transformation.
    <xsl:template match="doc">
      <p>
        <a href={$destdir}><xsl:value-of select="@label"/><a>
      </p>

      <pipe:pipeDocument   source="{@source}" target="{$destdir/@id}">
        <stylesheet href="ss1.xsl">
          <param name="doc-id" value="@id"/>
        </stylesheet>
        <stylesheet href="ss2.xsl"/>
      </pipe:pipeDocument>

    </xsl:template>
Notes: The base URI for the source attribute is the XML "book" document. The target attribute is taken as is (the base is the current user directory from which this transformation is being run). The stylsheet containg the extension element is the base URI for the stylesheet hrefs.
| Variation: using pipeDocument in an empty stylesheet |
| Suppose you want to pipe a document through a series of transformations. You can use the pipeDocument extension element to perform this operation by placing the extension element in an otherwise empty stylesheet. The following stylesheet is used to merge the Xalan documents into a book (the first transformation), and transform the book into a tree of formatting objects, which can then be used to generate a PDF file. This transformation is invoked as follows: `java org.apache.xalan.xslt.Process -in printbook.xml` `-param source printbook.xml` `-param target xalanbook.fo` There is no XML input document or output document for the primary transformation, which does no more than invoke the extension element.
    <?xml version='1.0'?>

    <xsl:stylesheet version="1.0"
                    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                    xmlns:pipe="http://xml.apache.org/xalan/PipeDocument"
                    extension-element-prefixes="pipe">

    <xsl:param name="source"/>
    <xsl:param name="target"/>

    <xsl:template match="/">

      <pipe:pipeDocument
            source="{$source}"
            target="{$target}">
        <stylesheet href="printbook_assemble.xsl"/>
        <stylesheet href="bkbook8x11_xalan.xsl"/>
      </pipe:pipeDocument>

    </xsl:template>

    </xsl:stylesheet>
| evaluate |
| Implemented in org.apache.xalan.lib.Extensions, `evaluate (xpath-expression)` function returns the result of evaluating the xpath-expression in the current XPath expression context (automatically passed in by the extension mechanism). Use the evaluation extension function when the value of the expression is not known until run time.
| Although you can still use the evaluate extension function in the main Extensions class, the preferred solution is to use the same function in the EXSLT dynamic package. This will make your stylesheet more portable across XSLT processors that support EXSLT extensions.
| tokenize |
| Implemented in org.apache.xalan.lib.Extensions, `tokenize (tokenize-string, delimiters)` or `tokenize (tokenize-string)` function returns a node-set containing one text node for each token in the tokenize-string. The delimiters determine which characters are used to divide the tokenize-string into individual tokens. If you do not include the delimiters argument, the function uses tab (&#x09), linefeed (&#x0A), return (&#x0D), and space (&#x20) as delimiters. if tokenize-string is an empty string or contains only delimiters, the result is an empty node-set.
| Although you can still use the tokenize extension function in the main Extensions class, the preferred solution is to use the same function in the EXSLT strings package. This will make your stylesheet more portable across XSLT processors that support EXSLT extensions.

Copyright © 2006 The Apache Software Foundation. All Rights Reserved.