Generate GUID in XSLT
Asked Answered
C

4

10

I need to generate a GUID with XSLT and if needed C#, does anyone know how to best do this?

It is to generate unique IDs for HTML items.

Contemporize answered 31/3, 2011 at 0:50 Comment(1)
There is a short XPath expression for this, See: https://mcmap.net/q/716911/-xslt-generate-uuidSanguinaria
A
3

The XSLT generate-id function returns a string that uniquely identifies a node in the document. Note these warnings from the spec:

An implementation is under no obligation to generate the same identifiers each time a document is transformed. There is no guarantee that a generated unique identifier will be distinct from any unique IDs specified in the source document.

However, if all you need is to uniquely identify each element in your output, then generate-id is sufficient.

Antimatter answered 31/3, 2011 at 0:54 Comment(2)
Thanks for the feedback but the xslt file will be called multiple times on the one page generating one item per time so I don;t think the generate-id would work. ANy other ideas?Contemporize
@Contemporize - See if this helps: #4510162Antimatter
F
1

C# provides a handy Guid.NewGuid() static method. I'd expect any XSLT implementation would heavily leverage some system-specific component since Guids are often generated in part based on hardware/MAC address/etc. on the underlying machine.

Faison answered 31/3, 2011 at 0:54 Comment(2)
I know about the Guid.NewGuid but how would I call that from XSLT?Contemporize
One way is via a XSL extension method like here: pedautreppe.com/post/Calling-C-function-in-XSL.aspxFaison
C
1

I ended up just using an extension method and wrapping Guid.NewGuid() in a static method, then calling this from my XSLT, it was easy enough once I figured out how extension methods work.

Contemporize answered 31/3, 2011 at 3:32 Comment(0)
Y
0

With C#, it can be achieved easily with Script Blocks Using msxsl:script.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:msxsl="urn:schemas-microsoft-com:xslt"
  xmlns:user="urn:my-scripts">
  <msxsl:script language="C#" implements-prefix="user">
  <![CDATA[
  public string getguid(){
     return Guid.NewGuid().ToString();
  }
  ]]>
  </msxsl:script>
  <xsl:template match="data">
    <Guid><xsl:value-of select="user:getguid()"/></Guid>
  </xsl:template>
</xsl:stylesheet>
Yellowstone answered 7/11, 2017 at 2:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.