2008-08-14

Extending standard stylesheet functions

The eXtensible Stylesheet Language for Transformations comes with its own set of functions, but Xalan, the XSLT processor shipped with Novelang support additional functions. Here is how it works, for function that converts numbers into words. First we define a static method (the most simple approach) in some Java class, doing the conversion we need. Parameters are: the number, the name of the language, if we want lower or upper case or capitals.
package novelang.rendering.xslt;

public class XsltFunctions {

  public static String numberAsText(
      Object numberObject,
      Object localeNameObject,
      Object caseObject
  ) {
  // ...
  }

}
The class must appear in the Novelang classpath (Java developers know what it means). In the stylesheet we add a special namespace that we call "nlx" like "NoveLang eXtensions":
<xsl:stylesheet
    version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:fo="http://www.w3.org/1999/XSL/Format"
    xmlns:n="http://novelang.org/book-xml/1.0"
    xmlns:xalan="http://xml.apache.org/xalan"
    xmlns:nlx="xalan://novelang.rendering.xslt.XsltFunctions"
 >
  ...
Here is how looks the call to convert a number into words:
  <xsl:value-of 
      select="nlx:numberAsText(43,'EN','capital')" />
Of course function calls (like position()) can replace our litteral number ("43"). The complete example is here and also contains a nice trick for hiding page numbers when they are not welcome. This function is useful for giving a special touch to lists or chapter numbers but we can imagine many other usages.

No comments: