C# and XSLT extension objects
May 14th, 2007 | Posted in .Net, Development | 1 Comments
Recently, I needed to transform an XML feed using C#. I wrote the XSLT script and it all worked ok.
One of the parts of the page took a TITLE and passed it to a Javascript function which then passed it to a flash file. This one particular record had a single quote, which as all developers know, will break everything within a 3 mile radius.
Trawling the MSDN rainforest led me to discover that you could pass parameters from the C# class which was carrying out the transformation, so I wondered if you could call methods in C# from the XSLT and behold you could.
The key was the AddExtensionObject method.
-
// Load XML document
-
-
// Create trans object
-
-
-
//load the Xsl
-
myXslTrans.Load("c:/myfile.xslt") ;
-
-
// Create and add XSLT extension
-
argsList.AddExtensionObject("urn:myObj", myObj);
-
myXslTrans.Transform(myXPathDoc,argsList, sw);
Then as part of your xsl stylesheet declaration add:
-
<xsl :stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
-
xmlns:myObj="urn:myObj"></xsl>
Whereas before this would throw an error:
-
<a href="#" onclick="return callExternalInterface(’{title}’);"></a>
By adding the XSLT extension object I could now do this:
-
<a href="#" onclick="return callExternalInterface(’{myObj:makeJsSafe(title)}’);"></a>












Thanks alot. Finally found some answers after googling this subject for days. Thanks.