sanjay
sanjay

Reputation: 1020

XSLT - Add incrementing id attribute to the nodes

I have an xml like this,

<doc>
  <section>1<section>
  <section>1<section>
  <p>22</p>
  <p>22</p>
  <p>22</p>
  <footer></footer>
  <footer></footer>
  <footer></footer>
</doc>

what I need to do id add new attribute to <footer> nodes. So the output would be

<doc>
   <section>1<section>
   <section>1<section>
   <p>22</p>
   <p>22</p>
   <p>22</p>
   <footer id="number-1"></footer>
   <footer id="number-2"></footer>
   <footer id="number-3"></footer>
 </doc>

I can add new attribute to <footer> node but the problem I'm facing is add incrementing ids in XSLT.

<xsl:template match="footer">
    <xsl:copy>
        <xsl:attribute name="id"><xsl:value-of select="'number-'[position()]"/></xsl:attribute>
        <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
</xsl:template>

I've tried to use xsl variable but since it's cannot change like other languages i couldn't do it. also I tried with position() function but it only gives position of the current node.so i this case id numbers stating from 6.

can you suggest me an solution. Thanks in advance

Upvotes: 1

Views: 355

Answers (1)

Joel M. Lamsen
Joel M. Lamsen

Reputation: 7173

you could use

<xsl:attribute name="id">
    <xsl:value-of select="'number-'"/>
    <xsl:number level="any"/>
</xsl:attribute>

Upvotes: 2

Related Questions