I have the following xml:
<policy>
<games>
<game startTime="11:00"/>
<game startTime="11:20"/>
<game startTime="11:40"/>
</games>
<games>
<game startTime="11:10"/>
<game startTime="11:30"/>
<game startTime="11:50"/>
</games>
</Policy>
I am trying to write an xslt that will add a new attribute to each game node and add the value in time order e.g.
<policy>
<games>
<game startTime="11:00" id="1"/>
<game startTime="11:20" id="3"/>
<game startTime="11:40" id="5"/>
</games>
<games>
<game startTime="11:10" id="2"/>
<game startTime="11:30" id="4"/>
<game startTime="11:50" id="6"/>
</games>
</policy>
I need the game nodes to stay in their current order so I'm not sure an xsl:sort would work.
At the moment I have this which obviously just numbers them in their current order and won't take account of the time attribute:
<xsl:template match="game">
<xsl:copy>
<xsl:attribute name="id">
<xsl:value-of select="count(preceding::game) + 1"/>
</xsl:attribute>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
I hope there is a better way than this:
<xsl:template match="game">
<xsl:copy>
<xsl:variable name="time" select="@startTime" />
<xsl:for-each select="//game">
<xsl:sort select="@startTime" />
<xsl:if test="current()/@startTime = $time">
<xsl:attribute name="id">
<xsl:value-of select="position()"/>
</xsl:attribute>
</xsl:if>
</xsl:for-each>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With