Increment counter based on condition in XSLT 1.0

226 Views Asked by At

How Can I increment the counter based on condition and use that counter to test another condition and render some statement? Here is my input XML -

<order>
            <orderId>Order1</orderId>
            <OrderObject>
                <OrderType>30</OrderType>
                <ObjectID>obj1</ObjectID>
            </OrderObject>
            <OrderObject>
                <OrderType>30</OrderType>
                <ObjectID>obj2</ObjectID>
            </OrderObject>
            <OrderObject>
                <OrderType>40</OrderType>
                <ObjectID>obj3</ObjectID>
            </OrderObject>
</order>

This is the XSLT what I am trying -

<xsl:variable name="counter" select="'1'"/>
        <xsl:variable name="length" select="'5'"/>
        <xsl:for-each select="order/OrderObject">
             <xsl:choose>
                                <xsl:when test="OrderType='30">
                                    {
                                     ObjectId : <xsl:value-of select="ObjectID"/>
                                    }
                                    counter = $counter+1;
                                    <xsl:choose>
                                    <xsl:when test="$counter < $length">
                                      <xsl:text>;</xsl:text>
                                    
                                </xsl:when>
                            </xsl:choose>
                                    
                                </xsl:when>
                            </xsl:choose>
        </xsl:for-each>

Expected Output-

                            {
                            
                                    "ObjectId": "obj1"   
                            };
                            {
                            
                                    "ObjectId": "obj2"
                            }
1

There are 1 best solutions below

1
On

Just process e.g. <xsl:for-each select="order/OrderObject[OrderType = 30]">, then inside you can check position() &lt; 5.

An alternative approach is not to suffix any but the last item with ; but to prefix any but the first item:

  <xsl:for-each select="order/OrderObject[OrderType = 30]">
     <xsl:if test="position() > 1">;</xsl:if>
     ...
  </xsl:for-each>