<?xml version="1.0" encoding="iso-8859-1"?> <?xml-stylesheet href="../../make-menu.xsl" type="text/xsl"?><html> <head> <this-is section="extensibility" page="integratedfunctions" subpage="ext-fns-N"/> <!-- Generated at 2011-12-09T20:47:22.916Z--><title>Saxonica: XSLT and XQuery Processing: .NET extension functions</title> <meta name="coverage" content="Worldwide"/> <meta name="copyright" content="Copyright Saxonica Ltd"/> <meta name="title" content="Saxonica: XSLT and XQuery Processing: .NET extension functions"/> <meta name="robots" content="noindex,nofollow"/> <link rel="stylesheet" href="../../saxondocs.css" type="text/css"/> </head> <body class="main"> <h1>.NET extension functions</h1> <p>The API for integrated .NET extension functions is available via the .NET classes <code>ExtensionFunctionDefinition</code> and <code>ExtensionFunctionCall</code>, both 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 s9api <code>Processor</code>, and then invokes it from an XPath expression:</p> <div class="codeblock" style="border: solid thin; background-color: #B1CCC7; padding: 2px"> <pre> <code> public class Sqrt : ExtensionFunctionDefinition { public override QName FunctionName { get { return new QName("http://math.com/", "sqrt") }; } public override int MinimumNumberOfArguments { get { return 1 }; } public override int MaximumNumberOfArguments { get { return 1 }; } public override XdmSequenceType[] ArgumentTypes { get { return new XdmSequenceType[] { new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_DOUBLE), '?') } } } public override XdmSequenceType ResultType(XdmSequenceType[] ArgumentTypes) { return new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_DOUBLE), '?'); } public override bool TrustResultType { get { return true }; } public override ExtensionFunctionCall MakeFunctionCall() { return new SqrtCall(); } } public class SqrtCall : ExtensionFunctionCall { public override IXdmEnumerator Call(IXdmEnumerator[] arguments, DynamicContext context) { Boolean exists = arguments[0].MoveNext(); if (exists) { XdmAtomicValue arg = (XdmAtomicValue)arguments[0].Current; double val = (double)arg.Value; double sqrt = System.Math.Sqrt(val); XdmAtomicValue result = new XdmAtomicValue(sqrt); return (IxdmEnumerator)result.GetEnumerator(); } else { return EmptyEnumerator.INSTANCE; } } } Processor proc = new Processor(); proc.RegisterExtensionFunction(new Sqrt()); XPathCompiler xpc = proc.NewXPathCompiler(); xpc.DeclareNamespace("mf", "http://math.com/"); XdmItem result = xpc.EvaluateSingle("mf:sqrt(2)", null); Console.WriteLine("Square root of 2 is " + result); </code> </pre> </div> <p>Full details of the interface are defined in the .NET API documentation.</p> <table width="100%"> <tr> <td> <p align="right"><a class="nav" href="../functions.xml">Next</a></p> </td> </tr> </table> </body> </html>