Written by
Peter Gregory
For umbraco versions:
Not Version relatedXSLT Example
Learn how extend XSLT with your own custom C# or JavaScript functions
The following is an example of how to extend your XSLT using C#. This is an example of using a C# extension to validate a macro property that a user types when putting the macro onto either a template or into the rich text editor. We want to make sure that the number entered is between 1 and 5 but if it is outside this range set it at 5.
Example XSLT with C# extension
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xsl:Stylesheet [ <!ENTITY nbsp " "> ]>
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxml="urn:schemas-microsoft-com:xslt"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:umbraco.library="urn:umbraco.library"
xmlns:mycustomprefix="urn:mycustomprefix"
exclude-result-prefixes="msxml umbraco.library mycustomprefix msxsl">
<xsl:output method="xml" omit-xml-declaration="yes"/>
<msxsl:script language="CSharp" implements-prefix="mycustomprefix">
<![CDATA[
public int? testNumber(int? num)
{
if(num> 5 || num<= 0 || num== null)
{
return 5;
}
else
{
return num;
}
}
]]>
</msxsl:script>
<xsl:param name="currentPage"/>
<xsl:variable name="numberToTest" select="mycustomprefix:testNumber(number(/macro/numberToTest))"/>
<xsl:template match="/">
<!-- start writing XSLT -->
<xsl:value-of select="$numberToTest"/>
</xsl:template>
</xsl:stylesheet>
The important pieces and the C# itself are bold so you can better see how to implement your custom code.
You are not limited to the core ASP.NET language either. You can implement any of your own custom .net libraries.
This is only a very simple example but it opens up a world of possibilities for building function right into your XSLT.