I have an XML file with many nodes, and each different node has to have a sequence number. How can I achieve this with XSLT 3.0?
Input example:
<root>
<a>x</a>
<a>x</a>
<c>x</c>
<d>x</d>
<a>x</a>
<c>x</c>
<d>x</d>
<b>x</b>
<a>
<x>.</x>
<b>.</b>
</a>
</root>
Output example:
<root serial='1'>
<a serial='1'>x</a>
<a serial='2'>x</a>
<c serial='1'>x</c>
<d serial='1'>x</d>
<a serial='3'>x</a>
<c serial='2'>x</c>
<d serial='2'>x</d>
<b serial='1'>x</b>
<a serial='4'>
<x serial='1'>.</x>
<b serial='2'>.</b>
</a>
</root>
CodePudding user response:
You should be able to use xsl:number
to do this...
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:mode on-no-match="shallow-copy"/>
<xsl:template match="*">
<xsl:copy>
<xsl:attribute name="serial">
<xsl:number/>
</xsl:attribute>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Working example: http://xsltfiddle.liberty-development.net/gVTWaA4/2