XML technologies / XSLT / XSLT Kochbuch / Extending and embedding XSLT / Saxon extension functions

(Excerpt from "XSLT Kochbuch" by Sal Mangano)

XSLT 1.0 (Saxon version 6.5.4)

With Saxon, you can access extension functions in Java using the interface defined in the draft XSLT 1.1 standard.

At present, Java is the only extension language supported by Saxon, so extension-function bindings are defined along the lines of the following examples:

<xsl:stylesheet version="1.1" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:Math="java:java.lang.Math" exclude-result-prefixes="Math">
  <xsl:script implements-prefix="Math" xmlns:Math="java:java.lang.Math" language="java" src="java:java.lang.Math"/>

The naming convention used here for the namespace is not strictly necessary. If it is followed, however, the xsl:script element becomes optional. If you need to access an extension only once, you can therefore write something like this:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:variable name="PI" select="4 * Math:atan(1.0)" xmlns:Math="java:java.lang.Math"/>
  <!-- ... -->
</xsl:stylesheet>

Here, the namespace encodes the binding to the Java implementation rather than the xsl:script. Note that these binding methods are independent. If you use the xsl:script element, the namespace content does not matter. Conversely, if you omit the xsl:script, the namespace serves solely to bind the Java implementation.

XSLT 2.0 (Saxon version 8.x)

The mechanism for executing Java-based extension functions is largely the same as in Saxon 6.5.4. However, the saxon:script element is deprecated and, according to the product website, may be removed in a future release. The preferred method is to declare a top-level namespace of the form java:, followed by the fully qualified class name.

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:math="java:java.lang.Math" exclude-result-prefixes="math">
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
  <xsl:template match="/">
    <pi><xsl:value-of select="4 * math:atan(1.0)"/></pi>
  </xsl:template>
</xsl:stylesheet>

  

 

 

 

back to top