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

Get XSLT Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.