XML technologies / XSLT / XSLT Cookbook / Extending and embedding XSLT / XSLT with JavaScript

(Excerpt from “XSLT Kochbuch” by Sal Mangano)

Problem

You want to use JavaScript to implement functionality missing from XSLT.

Solution

The following examples exploit the ability of Xalan-Java 2 to execute scripting languages such as JavaScript. A typical JavaScript extension calls a function built into neither XSLT nor XPath. Trigonometric functions are a common example:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xalan="http://xml.apache.org/xslt" xmlns:trig="http://www.ora.com/XSLTCookbook/extend/trig">
  <xsl:output method="text"/>
  <xalan:component prefix="trig" functions="sin">
    <xalan:script lang="javascript">function sin (arg){ return Math.sin(arg);}</xalan:script>
  </xalan:component>
  <xsl:template match="/">The sin of 45 degrees is <xsl:text/><xsl:value-of select="trig:sin(3.14159265 div 4)"/></xsl:template>
</xsl:stylesheet>

JavaScript lets you implement functions with side effects and objects with internal state. (I should be ashamed of suggesting this! Seriously, though, once you go beyond XSLT’s boundaries, you no longer have to play by its rules, but you must accept the consequences.)

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xalan="http://xml.apache.org/xslt" xmlns:count="http://www.ora.com/XSLTCookbook/extend/counter">
  <xsl:output method="text"/>
  <xalan:component prefix="count" functions="counter nextCount resetCount makeCounter">
    <xalan:script lang="javascript">
      function counter(initValue)
      {
        this.value = initValue ;
      }

      function nextCount(ctr)
      {
        return ctr.value++ ;
      }
      function resetCount(ctr, value)
      {
        ctr.value = value  ;
        return "" ;
      }

      function makeCounter(initValue)
      {
        return new counter(initValue) ;
      }
    </xalan:script>
  </xalan:component>
  <xsl:template match="/">
    <xsl:variable name="aCounter" select="count:makeCounter(0)"/>
    Count: <xsl:value-of select="count:nextCount($aCounter)"/>
    Count: <xsl:value-of select="count:nextCount($aCounter)"/>
    Count: <xsl:value-of select="count:nextCount($aCounter)"/>
    Count: <xsl:value-of select="count:nextCount($aCounter)"/>
    <xsl:value-of select="count:resetCount($aCounter,0)"/>
    Count: <xsl:value-of select="count:nextCount($aCounter)"/>
  </xsl:template>
</xsl:stylesheet>

In most implementations, this code produces the following:

   Count: 0    Count: 1    Count: 2    Count: 3    Count: 0

A processor that does not expect side effects may change the evaluation order, undermining the expected results.

The following example accesses JavaScript’s regular expression library:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xalan="http://xml.apache.org/xslt" xmlns:regex="http://www.ora.com/XSLTCookbook/extend/regex">
  <xsl:output method="text"/>
  <xalan:component prefix="regex" functions="match leftContext rightContext getParenMatch makeRegExp">
    <xalan:script lang="javascript">
      function Matcher(pattern)
      {
        this.re = new RegExp(pattern) ;
        this.re.compile(pattern) ;
        this.result="" ;
        this.left="" ;
        this.right="" ;
      }

      function match(matcher, input)
      {
        matcher.result = matcher.re.exec(input) ;
        matcher.left = RegExp.leftContext ;
        matcher.right = RegExp.rightContext ;
        return matcher.result[0] ;
      }

      function leftContext(matcher)
      {
        return matcher.left ;
      }

      function rightContext(matcher)
      {
        return matcher.right ;
      }

      function getParenMatch(matcher, which)
      {
        return matcher.result[which] ;
      }

      function makeRegExp(pattern)
      {
        return new Matcher(pattern) ;
      }
    </xalan:script>
  </xalan:component>
  <xsl:template match="/">
    <xsl:variable name="dateParser" select="regex:makeRegExp('(\d\d?)[/-](\d\d?)[/-](\d{4}|\d{2})')"/>
    Match: <xsl:value-of select="regex:match($dateParser,'I was born on 05/03/1964 in New York City.')"/>
    Left: <xsl:value-of select="regex:leftContext($dateParser)"/>
    Right: <xsl:value-of select="regex:rightContext($dateParser)"/>
    Month: <xsl:value-of select="regex:getParenMatch($dateParser, 1)"/>
    Day: <xsl:value-of select="regex:getParenMatch($dateParser,2)"/>
    Year: <xsl:value-of select="regex:getParenMatch($dateParser,3)"/>
  </xsl:template>
</xsl:stylesheet>

This example produces the following result:

   Match: 05/03/1964    Left: I was born on    Right: in New York City.    Month: 05    Day: 03    Year: 1964

Xalan also lets you create JavaScript-based extension elements. The following element executes its content n times. This is useful for duplicating strings or structures, or as a simple loop construct:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xalan="http://xml.apache.org/xslt" xmlns:rep="http://www.ora.com/XSLTCookbook/extend/repeat" extension-element-prefixes="rep">
  <xsl:output method="xml"/>
  <xalan:component prefix="rep" elements="repeat">
    <xalan:script lang="javascript">
      <![CDATA[
        function repeat(ctx, elem)
        {
          // Hole Attributwert n als Integer
          n = parseInt(elem.getAttribute("n")) ;
          // Hole Transformer, der für die Ausführung von Knoten benötigt wird
          xformer = ctx.getTransformer( ) ;
          // Führe Inhalt des repeat-Elements n-mal aus
          for(var ii=0; ii < n; ++ii)
        {
          node = elem.getFirstChild( ) ;
          while(node)
          {
            node.execute(xformer) ;
            node = node.getNextSibling( ) ;
          }
        }
        // Der Rückgabewert wird in die Ausgabe eingefügt, gib also null zurück, um das zu verhindern.
        return null ;
      }
    ]]>
    </xalan:script>
  </xalan:component>
  <xsl:template match="/">
    <tests>
      <!-- Dupliziere Text -->
      <test1><rep:repeat n="10">a</rep:repeat></test1>
      <!-- Dupliziere Struktur -->
      <test2>
        <rep:repeat n="10">
          <Malady>
            <FirstPart>Shim's</FirstPart>
            <SecondPart>Syndrome</SecondPart>
          </Malady>
        </rep:repeat>
      </test2>
      <!-- Wiederhole die Ausführung des XSLT-Codes (genau das, was wir in test1 und test2 gemacht haben). -->
      <test3>
        <rep:repeat n="10">
          <xsl:for-each select="*">
            <xsl:copy/>
          </xsl:for-each>
        </rep:repeat>
      </test3>
    </tests>
  </xsl:template>
</xsl:stylesheet>

Discussion

Implementing extensions in JavaScript or another embedded scripting language is tempting: although you must switch languages mentally, you need neither another development environment nor a separate compiler. Perhaps the greatest advantage is that languages such as JavaScript and VBScript are very easy to learn. (Before writing this book, I could actually have counted all the JavaScript lines I had ever written on two hands and a few toes.)

The challenge with script-based extensions is the generally sparse documentation on connecting XSLT to scripts. A few pointers are therefore appropriate here. Most of this information is available in the documentation on Xalan extensions, but it is easily overlooked when you are in a hurry to get something working.

First, script-based extensions are possible only in Xalan-Java, not Xalan C++.

Second, make sure you add bsf.jar and js.jar (for JavaScript) to your class path, either on the command line when invoking Java from a Unix shell,

java -cp /xalan/bin/xalan.jar:/xalan/bin/xercesImpl.jar:/xalan/bin/bsf.jar: /xalan/bin/js.jar org.apache.xalan.xslt.Process -in input.xml -xsl trans.xslt

or in the environment variable CLASSPATH:

export CLASSPATH=/xalan/bin/xalan.jar:/xalan/bin/xercesImpl.jar:/xalan/bin/bsf.jar:/xalan/bin/js.jar

On Windows, replace the colons separating paths with semicolons and use set instead of export.

Third, note that js.jar is not part of the Xalan distribution. You must obtain it separately from Mozilla.org.

After configuring your environment correctly, you must set up your stylesheet to meet Xalan’s requirements for script-based extensions. The introduction to this chapter gives the details.

Extension functions are much easier to implement than extension elements; the examples under “Solution”, together with the Xalan documentation, should suffice. The rest of this section focuses on extension elements.

When the function associated with an extension element is called, it automatically receives two objects. The first is a context of type org.apache.xalan.extensions.XSLProcessorContext. This object provides access to several useful objects, including the context node, stylesheet object and transformer. It also implements the function outputToResultTree(Stylesheet stylesheetTree, java.lang.Object obj), which can write data to the result tree. Access from JavaScript to all these Java-based objects is a feature of the Bean Scripting Framework, included in bsf.jar.

The second object is an instance of org.apache.xalan.templates.ElemExtensionCall. This object represents the extension element itself. You can extract the attributes and child elements your script needs to implement the extension’s functionality. This uses standard DOM function calls, such as getAttribute( ), getFirstChild( ), getLastChild( ) and so on.

There is hardly any limit to what a script-based extension element can do. You simply have to be able and willing to dig through Xalan-Java’s source code and documentation to find out how to make it do what you want. However, use script-based extensions only for simple tasks, since they are considerably slower than native Java extensions.

  

 

 

 

back to top