Generate GUID in XSLT
I need to generate a GUID wit开发者_开发技巧h XSLT and if needed C#, does anyone know how to best do this?
It is to generate unique IDs for HTML items.
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.
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.
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.
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>
精彩评论