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

Adding Extension Functions Using Java

Problem

You want to add your own custom extension functions written in Java.

Solution

This chapter’s introduction covered the mechanism for binding the stylesheet to the Java implementations, so this section concentrates on examples.

Chapter 2 showed how to convert numbers from base 10 to other bases (such as base 16 (hex)). You can implement a hex converter in Java easily:

package com.ora.xsltckbk.util;
   
public class HexConverter 
{
   
  public static String toHex(String intString) 
  {
    try 
    {
       Integer temp = new Integer(intString) ;
       return new String("0x").concat(Integer.toHexString(temp.intValue(  ))) ;
     } 
     catch (Exception e) 
    {
       return new String("0x0") ;
     }
  }
}

You can probably tell by the way the return value is formatted with a leading 0x that this particular function will be used in a code-generation application. The following example shows how it might be used:

<?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:hex="xalan://com.ora.xsltckbk.util.HexConverter" exclude-result-prefixes="hex xalan"> <xsl:template match="group"> enum <xsl:value-of select="@name"/> { <xsl:apply-templates mode="enum"/> } ; </xsl:template> <xsl:template match="constant" mode="enum"> <xsl:variable name="rep"> <xsl:call-template name="getRep"/> </xsl:variable> <xsl:value-of select="@name"/> = <xsl:value-of select="$rep"/> <xsl:if test="following-sibling::constant"> ...

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