Page 1 of 1

Breaking for-each loop on a conditional base

Posted: Wed Oct 30, 2019 5:17 pm
by javauser007
Hello All,

I'm new to xslt 2.0, I would like to set the value to a variable in for-each loop only once (means if the value set, I want to come out of the loop).

For now it keep iterating for all the users. I just want to come out of the loop once the value set (immediately after my first attemp). I'm not sure how to break if the value set once.

Can you please help me on the below code ?

XSLT Code:

<xsl:variable name="v_first_name">
<xsl:for-each select="$emailList/emails/child::*">
<xsl:variable name="mailid" select="id" />
<xsl:for-each select="$userList/users/child::*">
<xsl:if test="emailid = $mailid">
<xsl:if test="firstname eq 'Antony'">

<xsl:value-of select="firstname" />

</xsl:if>

</xsl:if>
</xsl:for-each>

</xsl:for-each>

</xsl:variable>



<xsl:if test="$v_first_name != ''">

<first_name>
<xsl:value-of select="$v_first_name" />
</first_name>
</xsl:if>


XML O/p:

<first_name>AntonyAntonyAntonyAntony</first_name>


Expected XML O/P:

<first_name>Antony</first_name>


Note1: Please note that I'm using xslt 2.0 and my lists can have duplicates (So Antony can come twice, but I want only once (or unique)).
Note2: I also tried with position(), but couldn't find it work as the condition (<xsl:if test="firstname eq 'Antony'">) can match at any position.


Thanks in advance.

Re: Breaking for-each loop on a conditional base

Posted: Wed Oct 30, 2019 7:44 pm
by adrian
Hi,

There is no such a thing as break in an XSLT for-each loop. xsl:if/@test is pretty much all you can do. The other way would be to include this condition within the for-each/@select.

See Stack Overflow | How-to break a for-each loop in XSLT? for more ideas.

Regards,
Adrian

Re: Breaking for-each loop on a conditional base

Posted: Thu Oct 31, 2019 8:41 am
by javauser007
Thanks Adrian, this helped me.