Reputation: 33
I want to write some logic based on the index inside xsl:for-each loop for example.
<xsl:for-each select="address">
<if index is 0>
<EPAPARTMENT1> <xsl:value-of select="value" /> </EPAPARTMENT1>
<if>
<if index is 1>
<EPDEPARTMENT2> <xsl:value-of select="value" /> </EPDEPARTMENT2>
<if>
</xsl:for-each>
Please explain, how to get an index value inside xsl:for-each loop and how to use that with xsl:if
Thanks.
Upvotes: 3
Views: 4370
Reputation:
Alternatively, you can use xsl:element
to programmatically create new elements if there are more than 2 element names you want to output.
<xsl:for-each select="//address">
<xsl:variable name="p" select="position()" />
<xsl:element name="EPAPARTMENT{$p}">
<xsl:value-of select="value" />
</xsl:element>
</xsl:for-each>
<xml>
<address><value>AAA</value></address>
<address><value>BBB</value></address>
<address><value>CCC</value></address>
<address><value>DDD</value></address>
</xml>
<EPAPARTMENT1>AAA</EPAPARTMENT1>
<EPAPARTMENT2>BBB</EPAPARTMENT2>
<EPAPARTMENT3>CCC</EPAPARTMENT3>
<EPAPARTMENT4>DDD</EPAPARTMENT4>
Upvotes: 1
Reputation: 4238
When you are iterating over a node set you can use the position()
function to return the current index within the node set. Note that this index is 1-based. So in your case you would write something like:
<xsl:for-each select="address">
<xsl:if test="position() = 1">
<EPAPARTMENT1> <xsl:value-of select="value" /> </EPAPARTMENT1>
</xsl:if>
<xsl:if test="position() = 2">
<EPDEPARTMENT2> <xsl:value-of select="value" /> </EPDEPARTMENT2>
</xsl:if>
</xsl:for-each>
Upvotes: 6