How to generate a GUID in XSLT transformations

Posted on Wednesday, May 10, 2017 by Nicki

A recent task involved migrating tens of jobs from Control M to VisualCron. I 'm never in the mood for manual repetitive tasks, so the approach was taken to do it with XSLT, since both Control M and VisualCron support XML config schemas.

VisualCron expects various Ids to be GUIDs, and XSL has no built-in functionality to generate GUIDs, so a plan had to be made. I queried Google and found that one can write extension objects in C# and use them during the translation.

The code for to generate a GUID is very simple:

    public class TransformUtils
    {
        public string GenerateGuid()
        {
            return Guid.NewGuid().ToString();
        }
    }

This is then plugged into the transformation code like this:
            string xmlPath = txtXMLSource.Text;
            string xslPath = txtXSLSource.Text;
            StringBuilder output = new StringBuilder();

            
            XsltArgumentList arguments = new XsltArgumentList();
            arguments.AddExtensionObject("EPS:TransformUtils", new TransformUtils());
            
            using (StringWriter writer = new StringWriter(output))
            {
                XslCompiledTransform transform = new XslCompiledTransform();
                transform.Load(xslPath);
                transform.Transform(xmlPath, arguments, writer);
            }
Inside the xslt stylesheet the extension function can now be called:
<xsl:value-of select="TransformUtils:GenerateGuid()" />

I found a good sample and guide here