tags:

views:

63

answers:

2

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
Sorry, I have to say no. The task is trivial, I gave enough clues.
lexicore
<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
Thanks got it done.
Rachel
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
Thanks. Even i tried without the named template. It works.
Rachel
+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"&gt;

<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"&gt;
      <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
Thanks. Looks great!!
Rachel
@Marvin: This is needlessly complex. It gets a lot shorter when you do it the way @lexicore describes.
Tomalak