Creating "index" attribute element and incrementing it from 0
Posted: Tue Apr 05, 2022 7:46 pm
Hi, I have this input xml :
which I need to transform to this output xml :
So I need to add an attribute with name="index" and value="" will increment from 0. This new attribute should be created AFTER the <type>ABCDE</type> for 1st case, <type>PQRST</type> for 2nd case, <type>JKLMN</type> for 3rd case, and similarly for the future <type>...</type> attributes as well.
I need to use XSLT for the transformation. The current XSLT I have is this :
But I am not getting the desired output from this XSLT. Could someone kindly help me out with this?
Code: Select all
<root>
<type>randomtext</type>
<attribute name="ath value"/>
...
<attribute name="nth value"/>
<attribute name="initial">
<respondtag>
<tagtext name="valA">
<texts>
<type>ABCDE</type>
<attribute name="abc" value="def" />
</texts>
</tagtext>
<tagtext name="valB">
<texts>
<type>PQRST</type>
<attribute name="thj" value="trf" />
</texts>
</tagtext>
<tagtext name="valC">
<texts>
<type>JKLMN</type>
<attribute name="lop" value="pth" />
</texts>
</tagtext>
<tagtext name="...">
<texts>
<type>...</type>
<attribute name="type" value="..." />
</texts>
</tagtext>
</respondtag>
</attribute>
</root>
Code: Select all
<root>
<type>randomtext</type>
<attribute name="ath value"/>
...
<attribute name="nth value"/>
<attribute name="initial">
<respondtag>
<tagtext name="valA">
<texts>
<type>ABCDE</type>
<attribute name="abc" value="def" />
<attribute name="index" value="0" />
</texts>
</tagtext>
<tagtext name="valB">
<texts>
<type>PQRST</type>
<attribute name="thj" value="trf" />
<attribute name="index" value="1" />
</texts>
</tagtext>
<tagtext name="valC">
<texts>
<type>JKLMN</type>
<attribute name="lop" value="ptq" />
<attribute name="index" value="2" />
</texts>
</tagtext>
<tagtext name="...">
<texts>
<type>...</type>
<attribute name="type" value="..." />
<attribute name="index" value="..." />
</texts>
</tagtext>
</respondtag>
</attribute>
</root>
I need to use XSLT for the transformation. The current XSLT I have is this :
Code: Select all
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="texts">
<xsl:copy>
<xsl:copy-of select="*"/>
<attribute name="index" value="{position()-1}"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>