Developer FAQ
How to run a C# function in XSLT?
Answer:
You can add C# functions to your XSLT in 3 easy steps (please check sample code below or download source here):
- Add the namespace declarations:
xmlns:msxsl=urn:schemas-microsoft-com:xslt
andxmlns:user=urn:my-scripts
to the style sheet. - To avoid parsing errors declare your function inside a
CDATA
section within themsxsl:script
element. - Call your function with parameters like
<xsl:value-of select="user:GetDate('dddd, dd MMMM yyyy')"/>
Tips and Tricks:
- You can add required assemblies (DLL references), namespaces we are using with C# function inside
<msxsl:script />
block (checkSystem.Web
in our example) - Use
exclude-result-prefixes
"user" and "msxsl" to keep your output XHTML clean. - To obtain value from query string, use
System.Web.HttpContext.Current.Request.QueryString["Page"]
, instead ofRequest.QueryString["Page"]
.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" exclude-result-prefixes="xsl in lang user" xmlns:in="http://www.composite.net/ns/transformation/input/1.0" xmlns:lang="http://www.composite.net/ns/localization/1.0" xmlns:f="http://www.composite.net/ns/function/1.0" xmlns="http://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>
Please read related article "Fetching data in XSLTs using inline C#".
Detailed information about XSLT Stylesheet Scripting using <msxsl:script>
could be found here http://msdn.microsoft.com/en-us/library/533texsx(VS.71).aspx