Matthew PaveyFAITH, FAMILY, CODE
Coffee

Reusable XSLT Transformations in .NET: Parameters and Extension Objects

When working with XML data, binding it to one of the standard ASP.NET controls does not always give you the flexibility to display it the way you need, especially with hierarchical data more than a couple of levels deep. You can load the XML and parse through it to build your controls manually, but that gets difficult with complex hierarchies.

In those cases XSL is often the better answer. XSL is a family of recommendations for transforming and presenting XML documents:

  • XSLT, a language for transforming XML.
  • XPath, the expression language XSLT uses to refer to parts of an XML document.
  • XSL-FO, an XML vocabulary for specifying formatting semantics.

If you want to learn XSL properly, I recommend Michael Kay's XSLT Programmer's Reference. He is one of the leading experts on the subject, and you will see him turn up on forums explaining what XSL is and how it is meant to be used.

Over the years I have used XSL for re-transforming XML from one format to another, for advanced sorting, and for displaying hierarchical data in a very specific format. What I want to cover here is narrower: a pattern for wrapping XSL transformations in something reusable, so that the messy parts are handled once and configured rather than rewritten on every project.

The idea is a small wrapper class that can transform XML from either a file or a string passed in directly, and whose transform method is overloaded to accept either a simple path to an XSL file or a configuration object carrying more advanced settings.

Sometimes all you need is to pass in XML and an XSL path and get the result back:

Using Xsl As New Utilities.Xsl()
    News.Text = Xsl.TransformXml(Utilities.Xsl.XmlTypes.XmlData, XmlData, Server.MapPath("~/Test.xsl"))
End Using

The same thing using the configuration object, with no advanced settings:

Using Xsl As New Utilities.Xsl()
    Using XslConfig As New Utilities.Xsl.XslConfiguration(Server.MapPath("~/Test.xsl"))
        HtmlData = Xsl.TransformXml(Utilities.Xsl.XmlTypes.XmlData, XmlData, XslConfig)
    End Using
End Using

And the version that earns the configuration object, passing parameters into the transformation and supplying an extension object so the XSL can call back into your code:

Using Xsl As New Utilities.Xsl()
    Using XslConfig As New Utilities.Xsl.XslConfiguration()

        ' xsl file path
        XslConfig.XslFile = XslFile

        ' extension object with a function that will be accessible in our transformation
        XslConfig.ExtensionNameSpace = "urn:ext"
        XslConfig.ExtensionObject = New ExtensionObject

        ' parameters required in the xsl transformation
        XslConfig.SetXslParameterNames("Parameter1Name", "Parameter2Name")
        XslConfig.SetXslParameterValues("Parameter1Value", "Parameter2Value")

        ' transform the data
        HtmlData = Xsl.TransformXml(Utilities.Xsl.XmlTypes.XmlData, XmlData, XslConfig)

        ' check for errors
        If Xsl.ErrorDescription <> String.Empty Then
            HtmlData = Xsl.ErrorDescription
        End If

    End Using
End Using

For that last example to work you need to define the extension object:

Private Class ExtensionObject

    Public Function IsImageAvailable(ByVal Image As String) As String
        Return File.Exists(HttpContext.Current.Server.MapPath("~/Images/" & Image))
    End Function

End Class

And the transformation itself looks something like this:

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

  <xsl:output media-type="html" omit-xml-declaration="yes"/>

  <xsl:param name="Parameter1Name" />
  <xsl:param name="Parameter2Name" />

  <xsl:template match="/">
    Parameter1Name: <xsl:value-of select="$Parameter1Name"/><br/>
    Parameter2Name: <xsl:value-of select="$Parameter2Name"/><br/>

    <xsl:apply-templates select="//Row">
      <xsl:sort select="LastName"  data-type="text" order="ascending" />
      <xsl:sort select="FirstName" data-type="text" order="ascending" />
    </xsl:apply-templates>
  </xsl:template>

  <xsl:template match="Row">
    <xsl:variable name="ShowImage" select="ext:IsImageAvailable(Image)"/>

    <xsl:choose>
      <xsl:when test="$ShowImage='True'">
        <img src="Images/{Image}" />
      </xsl:when>
      <xsl:otherwise>
        <img src="Images/ImageNotAvailable.jpg" />
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

</xsl:stylesheet>

Two things tie the code and the stylesheet together. The xmlns:ext attribute on the xsl:stylesheet node matches the namespace set in the code behind:

XslConfig.ExtensionNameSpace = "urn:ext"

And that is what makes the custom function callable from inside the transformation:

<xsl:variable name="ShowImage" select="ext:IsImageAvailable(Image)"/>

The parameters work the same way: declared with xsl:param in the stylesheet, supplied by name and value from the calling code.

Wrapping all of this in a single reusable class means the transformation details get configured rather than rewritten, which has saved me a lot of repetition across projects.