Java in Xslt

<<TableOfContents: execution failed [Argument "maxdepth" must be an integer value, not "[3]"] (see also the log)>>

Intent

How to use java code in your xslt stylesheets

Motivation

Xslt is a declarative language that permits to express what you want, but not how you want. There are tasks for which it is well suited. There are others where it's a real mess. And there are tasks for which a library is already available in Java. The Xalan xslt processor support java language and permits to call any java class from the xslt code. Here is an example how to do date formatting with this technique

Implementation

This example permits you to format dates that respects the date and time format standart.

First, you must declare the namespace for the java class you want to use. It may be your class in its own package.

<xsl:stylesheet
    version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:sdf="http://xml.apache.org/xalan/java/java.text.SimpleDateFormat">

Then, you may create an instance of this class, with parameters if you want :

    <xsl:variable name="inputPattern">yyyy-MM-dd'T'HH:mm:ss.SSSZ</xsl:variable>
    <xsl:variable name="inputSdf" select="sdf:new($inputPattern)"/>

At last, you call a method for this instance. Be careful to the syntax. The instance on which you call the method is the first parameter, like in line 2 !!!

1    <xsl:variable name="inputDateString" select="."/>
2    <xsl:variable name="inputDate" select="sdf:parse($inputSdf,$inputDateString)"/>
3    <xsl:variable name="outputPattern" select="string($meta/format/pattern)"/>
4    <xsl:variable name="outputSdf" select="sdf:new($outputPattern)"/>
5    <xsl:value-of select="sdf:format($outputSdf,$inputDate)"/>

Finally, you will have the following stylesheet that converts a string with the provided pattern to the french one :

<xsl:stylesheet
    version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:sdf="http://xml.apache.org/xalan/java/java.text.SimpleDateFormat">

  <xsl:param name="inputPattern">yyyy-MM-dd'T'HH:mm:ss.SSSZ</xsl:param>
  <xsl:param name="outputPattern">dd/MM/yyyy</xsl:param>

  <xsl:variable name="inputSdf" select="sdf:new($inputPattern)"/>

  <xsl:template match="/">

    <xsl:variable name="inputDateString" select="."/>
    <xsl:variable name="inputDate" select="sdf:parse($inputSdf,$inputDateString)"/>
    <xsl:variable name="outputSdf" select="sdf:new($outputPattern)"/>

    <xsl:value-of select="sdf:format($outputSdf,$inputDate)"/>
  </xsl:template>

It's up to you now

Reference

More information

This web page is available in html format on http://www.bluexml.org. You may have help on cocoon or bluexml mailing lists.

JCKermagoret

Tips/JavaInXslt (last edited 2009-09-20 23:40:05 by localhost)