xlst script reference


How to run a C# function in XSLT?

You can add C# functions to your XSLT in 3 easy steps (please check sample code below or download source here):

  1. Add the namespace declarations: xmlns:msxsl=urn:schemas-microsoft-com:xslt and xmlns:user=urn:my-scripts to the style sheet.
  2. To avoid parsing errors declare your function inside a CDATA section within the msxsl:script element.
  3. Call your function with parameters like <xsl:value-of select="user:GetDate('dddd, dd MMMM yyyy')"/>

Tips and Tricks:

  1. You can add required assemblies (DLL references), namespaces we are using with C# function inside <msxsl:script /> block (check System.Web in our example)
  2. Use exclude-result-prefixes "user" and "msxsl" to keep your output XHTML clean.
  3. To obtain value from query string, use System.Web.HttpContext.Current.Request.QueryString["Page"], instead of Request.QueryString["Page"].

<xsl:stylesheet version="1.0" xmlns:xsl="https://www.w3.org/1999/XSL/Transform" exclude-result-prefixes="xsl in lang user" xmlns:in="https://www.composite.net/ns/transformation/input/1.0" xmlns:lang="https://www.composite.net/ns/localization/1.0" xmlns:f="https://www.composite.net/ns/function/1.0" xmlns="https://www.w3.org/1999/xhtml" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:user="urn:my-scripts"> 

 <msxsl:script language="C#" implements-prefix="user"> 

 <msxsl:assembly name="System.Web" /> 

 <msxsl:using namespace="System.Web" /> 

 <![CDATA[ public string GetDate(string DateFormat) { return DateTime.Now.ToString(DateFormat); } ]]> </msxsl:script> <xsl:template match="/"> <html> <head /> <body> <div> <xsl:value-of select="user:GetDate('dddd, dd MMMM yyyy')" /> </div> </body> </html> </xsl:template></xsl:stylesheet>