xml - XSLT - Add dynamic id and change attribute -


i have xml file follows,

<doc>   <a ref="foot"></a>   <a ref="foot"></a>   <a ref="foot"></a>   <a ref="end"></a>   <a ref="end"></a>   <a ref="end"></a> <doc> 

my requirement add dynamically increment id attribute <a> node have "end" attribute. , change "foot" attribute "end" result document be,

<doc>   <a ref="end" id="1"></a>   <a ref="end" id="2"></a>   <a ref="end" id="3"></a>   <a ref="end" id="4"></a>   <a ref="end" id="5"></a>   <a ref="end" id="6"></a> <doc> 

i able add dynamic id nodes , change "foot" attribute "end" id's added node have "end" attribute. nodes have attribute "foot" not add id. current output follows,

<doc>   <a ref="end"></a>   <a ref="end"></a>   <a ref="end"></a>   <a ref="end" id="1"></a>   <a ref="end" id="2"></a>   <a ref="end" id="3"></a> <doc> 

my xsl code follows,

//adds dynamic id's foot node  <xsl:template match="a/@ref[.='end']">    <xsl:attribute name="id">         <xsl:number count="a[@ref='end']" level="any"></xsl:number>    </xsl:attribute> </xsl:template>   //change attribute "foot" attribute "end"    <xsl:template match="a/@ref[. = 'foot']">         <xsl:attribute name="id">end</xsl:attribute>  </xsl:template> 

my problem how can add id's first 3 nodes. may use xsl variables i'm new xslt , couldn't thik of way how can use variables. if can "foot" attribute "end" attribute conversation first , add id's code run fine. have no idea of possible xslt.

can suggest me answer how can this?

thanks in advance.

here how can it:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/xsl/transform"                 version="2.0">    <xsl:output omit-xml-declaration="yes"/>    <!-- identity transform -->   <xsl:template match="@* | node()">     <xsl:copy>       <xsl:apply-templates select="@* | node()" />     </xsl:copy>   </xsl:template>    <!-- add sequential id attribute; set ref attribute value "end" -->   <xsl:template match="a">     <a ref="end">       <xsl:attribute name="id"><xsl:number/></xsl:attribute>     </a>   </xsl:template>  </xsl:stylesheet> 

output saxon:

<doc>   <a ref="end" id="1"/>   <a ref="end" id="2"/>   <a ref="end" id="3"/>   <a ref="end" id="4"/>   <a ref="end" id="5"/>   <a ref="end" id="6"/> </doc> 

Comments