Friday, August 1, 2014

Calling C# code from XSLT

When you do complex mapping especially with EDI / HL7 Schemas, we might not be able to achieve the desired mapping using out of box functoids. In such cases, we go for using Inline XSLT / Inline XSLT Call Template.
While using inline XSLT, there are some tasks which can be complex to develop using XSLT.
For example, what if I want to increment a variable by 2, for each input Record and map the resulting value to a Target element? In XSLT, we don’t have an option of using x=x+2.
In these cases, we can combine C# and XSLT to achieve the desired output.
Lets look at the sample example:
1. Create a Global Variable in a Scripting Functoid and write a method to increment the variable by 2, for each method call.

2. Leave the scripting Functoid as it is. It is not required to connect this to any input/output node.
3. Now place another scripting Functoid from Roolbox and select Inline XSLT Call Template and add your XSLT.
4. In order to call the above C# method from XSLT and get the incremented value, use the below line of code.
<xsl:variable name=”var:counter” select=”userCSharp:IncrementAndReturn()” />

5. Complete XSLT will look like below.
<xsl:template name=”MyXsltConcatTemplate”>
<xsl:for-each select=”Employees/Employee”>
<xsl:variable name=”var:counter” select=”userCSharp:IncrementAndReturn()” />
<xsl:value-of select=”$var:counter” />

6. Completed map will look like below

This way we can leverage C# features and combine it with the flexibility of XSLT and get the desired output.

No comments: