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’.
Kumana said,
December 14, 2009 @ 5:32 pm
I tried this with Saxon-HE 9.2 and get the following error.
{guid:NewGuid()}:
Cannot find a matching 0-argument function named
{clitype:System.Guid?partialname=mscorlib}NewGuid()
Do you know what might be the issue?
Thanks
Pete said,
May 31, 2010 @ 9:54 am
Saxon version 9.2 no longer seems to support this. I tried the previous version 9.1.0.8. and it worked fine.
BestKathlene said,
February 22, 2019 @ 4:10 am
I have noticed you don’t monetize your site, don’t waste your
traffic, you can earn extra cash every month.
If you want to read about this method, simply search in gooogle:
dracko’s tricks