Java extension functions: simple interface

The simple API for integrated Java extension functions is available via the s9api class ExtensionFunction. Here is an example that defines an extension function to calculate square roots, registers this extension function with the s9api Processor, and then invokes it from an XPath expression:

Processor proc = new Processor(false); ExtensionFunction sqrt = new ExtensionFunction() { public QName getName() { return new QName("http://math.com/", "sqrt"); } public SequenceType getResultType() { return SequenceType.makeSequenceType( ItemType.DOUBLE, OccurrenceIndicator.ONE ); } public SequenceType[] getArgumentTypes() { return new SequenceType[]{ SequenceType.makeSequenceType( ItemType.DOUBLE, OccurrenceIndicator.ONE)}; } public XdmValue call(XdmValue[] arguments) throws SaxonApiException { double arg = ((XdmAtomicValue)arguments[0].itemAt(0)).getDoubleValue(); double result = Math.sqrt(arg); return new XdmAtomicValue(result); } }; proc.registerExtensionFunction(sqrt); XPathCompiler comp = proc.newXPathCompiler(); comp.declareNamespace("mf", "http://math.com/"); comp.declareVariable(new QName("arg")); XPathExecutable exp = comp.compile("mf:sqrt($arg)"); XPathSelector ev = exp.load(); ev.setVariable(new QName("arg"), new XdmAtomicValue(2.0)); XdmValue val = ev.evaluate(); String result = val.toString();

Full details of the interface are defined in the Javadoc for class ExtensionFunction.

The main restriction of the simple interface is that the extension function has no access to static or dynamic context information. To avoid these restrictions, use the full interface described on the next page.