24 July 2007

Adding Custom Functions to XSL using XSLT Extensions

Many times it is our requirement to perform various types of processing in XSL file using functions. There are many in-built functions in XSL for doing various types of tasks like string manipulation, number calculations etc but sometimes we need to do some custom processing which can only be achieved by writing our own custom functions. These custom functions can be written in either JavaScript or in some other language. This BOK focuses on how to write these custom functions in a .NET compliant language (like VB.NET, C#) and then use it in our XSL file.

Here are the steps to achieve the same:-

1. Create the custom function in a class. If you need to write many custom functions, it is better to place these functions in a separate class; otherwise the function can be written in same class file as your calling code.
Here a separate class “XSLCustomFunctions” is created which has a function for date formatting.

Public Class XSLCustomFunctions
Public Function Format_Date(ByVal sDateTime As String) As DateTime
Return CDate(sDateTime)
End Function
End Class

Point to Note - Here class name is “XSLCustomFunctions” and custom function name is “Format_Date”

2. Create an object of the custom function class. This has to be done in the function where the XSL transform is being applied.

Dim oCustFunc As New XSLCustomFunctions
3. Now we need to create XML namespace declaration in the XSL file for this custom class
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:myCustFunc="urn:custFunc">

Point to Note – Here “myCustFunc” is the XML namespace which refers to “urn:custFunc”. This will be passed as XSL extension while adding XSL extension object in step 5

4. Use the custom function in the XSL at the required place. Please note that function is used in the format – “XML_NameSpace:CustomFunction”.

<xsl:value-of select="myCustFunc:Format_Date(Value)" />

5. Create an object of XSLT argument list in the VB.NET code and add extension object to it and then only apply the XSL transform.

Private Function ApplyXSLTransform(ByVal sXml As String) As String

Dim oArgsList As New XsltArgumentList
Dim oXmlDocument As New XmlDocument
Dim oXslTransform As New XslTransform
Dim oStringWriter As New System.IO.StringWriter
Dim oCustFunc As New XSLCustomFunctions

oXmlDocument.LoadXml(sXml)
oXslTransform.Load(Server.MapPath("xsl_doc.xsl"))

oArgsList.AddExtensionObject("urn:custFunc", oCustFunc)

oXslTransform.Transform(oXmlDocument, oArgsList, oStringWriter, Nothing)

Return oStringWriter.ToString
End Function

In this way, we can use our own custom functions created in VB.NET/C# in the XSL file.

1 comment:

Anonymous said...

Great work.