New here? Then you may want to subscribe to my rss feed. :)

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.

CSharp [Show Plain Code]:
  1. // Load XML document
  2. XPathDocument myXPathDoc = new XPathDocument("c:/myfile.xml") ;
  3.  
  4. // Create trans object
  5. XslCompiledTransform myXslTrans = new XslCompiledTransform() ;
  6.  
  7. StringBuilder sb = new StringBuilder();
  8. StringWriter sw = new StringWriter(sb);
  9.  
  10. //load the Xsl
  11. myXslTrans.Load("c:/myfile.xslt") ;
  12.  
  13. // Create and add XSLT extension
  14. XsltArgumentList argsList = new XsltArgumentList();
  15. myHelperObj myObj = new myHelperObj();
  16. argsList.AddExtensionObject("urn:myObj", myObj);
  17. myXslTrans.Transform(myXPathDoc,argsList, sw);

Then as part of your xsl stylesheet declaration add:

  1. <xsl :stylesheet version="1.0"  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  2.         xmlns:myObj="urn:myObj"></xsl>

Whereas before this would throw an error:

  1. <a href="#" onclick="return callExternalInterface(’{title}’);"></a>

By adding the XSLT extension object I could now do this:

  1. <a href="#" onclick="return callExternalInterface(’{myObj:makeJsSafe(title)}’);"></a>

One Response to “C# and XSLT extension objects”

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>