Archive for March, 2009

How to generate GUIDs in XSLT 2.0, using Saxon.NET

I have a project where I need to generate file names that are GUIDs. I’m using Saxon.NET. With the help of Google, I figured out how to do that, but it wasn’t immediately obvious. Hopefully this post will make the solution easier to find for other people trying to solve the same problem.

This is just one example of a .NET function you can access as an extension function in XSLT 2.0, so a more general-purpose treatment of .NET extension functions might be more useful. (I defer to “Writing extension functions for .NET” for that.) But if you’re like me, you spend most of your coding time within the safe, comfy confines of pure XSLT. And you do very little .NET development. So to ensure your continued comfort, here’s how you can generate a GUID in Saxon.NET (relevant parts highlighted):

<xsl:stylesheet version="2.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:guid="clitype:System.Guid?partialname=mscorlib"
  exclude-result-prefixes="guid">

  <xsl:output indent="yes"/>

  <xsl:template match="/">
    <guids>
      <guid>
        <xsl:value-of select="guid:NewGuid()"/>
      </guid>
      <guid>
        <xsl:value-of select="guid:NewGuid()"/>
      </guid>
      <guid>
        <xsl:value-of select="guid:NewGuid()"/>
      </guid>
    </guids>
  </xsl:template>

</xsl:stylesheet>

Here’s an example result from applying this stylesheet (to any input document):

<guids>
   <guid>6dbd3a72-ad74-429d-97ca-3056e8940813</guid>
   <guid>cea97da4-9de5-4fb5-a35e-ba04a0dee906</guid>
   <guid>41c89105-6cf7-4fd6-b17a-ed04235a4804</guid>
</guids>

All you do is call the .NET platform’s System.Guid.NewGuid() method as an extension function. The function’s namespace URI identifies for Saxon what assembly and object class you’re interested in (System.Guid in this case).

Thanks to M. David Peterson: I found this usage buried in a code example in his lucidly-titled blog post: if ((OOP + FP + AOP) == XSLT 2.0) then ‘Composable Language’ else ‘Try Again’.

Comments (3)

Some updates

Short blog post, in bullet points:

That’s all for now. See you again in 6 months. 🙂

Comments (1)