I want to add a unique attribute say "ind" to every tag in the xml. How do i do it using xsl. It need'nt be a sequence number. As long it is unique for every tag it is sufficient.
+3
A:
Take identity transformation, add template for elements in which add attribute with value generated by generate-id().
lexicore
2010-04-14 20:09:57
Sorry, I have to say no. The task is trivial, I gave enough clues.
lexicore
2010-04-14 20:42:43
<xsl:template match="@*|node()"> <xsl:copy> <xsl:call-template name="add-attribute"> </xsl:call-template> <xsl:apply-templates /> </xsl:copy></xsl:template><xsl:template name="add-attribute"> <xsl:attribute name="ind"> <xsl:value-of select="generate-id()" /></xsl:attribute></xsl:template></xsl:stylesheet>
Rachel
2010-04-14 20:46:24
Thanks got it done.
Rachel
2010-04-14 20:46:43
I'd do<xsl:template match="*" priority="10"> <xsl:copy> <xsl:attribute name="ind"> <xsl:value-of select="generate-id()" /> </xsl:attribute> <xsl:apply-templates /> </xsl:copy></xsl:template>instead of the the named template (in addition to the identity transform).
lexicore
2010-04-14 21:07:00
Thanks. Even i tried without the named template. It works.
Rachel
2010-04-15 00:56:18
+1
A:
Something like this?
It also uses a unique namespace for the attribute we are adding so we don't override any existing attributes with ours if they have the same name.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl" xmlns:mycomp="http://www.myuniquenamespace">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="node()">
<xsl:element name="{local-name()}" namespace="{namespace-uri()}">
<xsl:apply-templates select="@*"/>
<xsl:attribute name="someattr" namespace="http://www.myuniquenamespace">
<xsl:value-of select="generate-id()"/>
</xsl:attribute>
<xsl:apply-templates select="node()"/>
</xsl:element>
</xsl:template>
<xsl:template match="@* | text()">
<xsl:copy />
</xsl:template>
</xsl:stylesheet>
Hope this helps you on your way,
Marvin Smit
2010-04-14 21:09:13