Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSLT Number nodes without sorting

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>
like image 427
DasDave Avatar asked Oct 21 '22 21:10

DasDave


1 Answers

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>
like image 100
Rubens Farias Avatar answered Oct 24 '22 01:10

Rubens Farias