Frage

I'd like to transform XML file to have incremental counter in the output. I'm trying to do so but every approach fails. It needs to be dane in XSLT-1.0.

This is fragment of XML stylesheet which doesn't work, but you'll get the idea:

<tripSequence>
    <xsl:variable name="cnt" select="0"/>
    <xsl:for-each select="BODY/DBOUT/TRIP/PLANCOMPONENTS/*[starts-with(name(),'NO')]">
        <xsl:if test="TYPE = 'PICKUP' or TYPE = 'DELIVERY'">
            <numberInSequence><xsl:value-of select="$cnt"/></numberInSequence>
            <xsl:variable name="cnt" select="$cnt + 1"/>
        </xsl:if>
    </xsl:for-each>
</tripSequence>

How to put incremental value every time when if-condtion is met?

War es hilfreich?

Lösung

Variables in XSLT are actually constants. You can only apply different values to variables if you use recursion. To obtain what you want, you can simply print the position() of the node replacing the if test with a predicate in the loop:

<tripSequence>
    <xsl:for-each select="BODY/DBOUT/TRIP/PLANCOMPONENTS/*[starts-with(name(),'NO')][TYPE = 'PICKUP' or TYPE = 'DELIVERY']">
         <numberInSequence><xsl:number value="position()"/></numberInSequence>
    </xsl:for-each>
</tripSequence>

This will count only the actual nodes that match the for-each. If you use position() with the if test instead of the predicate, it will also record the positions of the elements that match the predicate and not the if, and may not be sequential.

The count starts at 1. If you want to count from zero, you have to subtract 1.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top