.NET extension functions: simple interface

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

public class SqrtSimple : ExtensionFunction { public XdmValue Call(XdmValue[] arguments) { if (!(arguments[0] is XdmEmptySequence)) { XdmAtomicValue arg = (XdmAtomicValue)arguments[0].ItemAt(0); double val = (double)arg.Value; double sqrt = System.Math.Sqrt(val); return new XdmAtomicValue(sqrt); } else { return XdmValue.MakeValue((double)0); } } public XdmSequenceType[] GetArgumentTypes() { return new XdmSequenceType[]{ new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_DOUBLE), '?') }; } public QName GetName() { return new QName("http://math.com/", "sqrtSimple"); } public XdmSequenceType GetResultType() { return new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_DOUBLE), ' '); } } Processor proc = new Processor(); proc.RegisterExtensionFunction(new SqrtSimple()); XPathCompiler xpc = proc.NewXPathCompiler(); xpc.DeclareNamespace("mf", "http://math.com/"); XdmItem result = xpc.EvaluateSingle("mf:sqrtSimple(2)", null); Console.WriteLine("Square root of 2 is " + result);

Full details of the interface are defined in the .NET API documentation.

The main restrictions of the simple interface are (a) that the extension function has no access to static or dynamic context information, and (b) that it does not support pipelined evaluation of the arguments or result. To avoid these restrictions, use the full interface described on the next page.