O'Reilly logo

XSLT Cookbook by Sal Mangano

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Extending XSLT with JavaScript

Problem

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

Solution

The following examples use Xalan Java 2’s ability to invoke scripting languages such as JavaScript. A typical use of a JavaScript-based extension invokes a function that is not native to XSLT or XPath. One common example is trigonometric functions:

<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>

With JavaScript, you can actually implement functions that have side effects and objects that maintain state:[30]

<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 "" ; } ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required