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