Breaking for-each loop on a conditional base

Here should go questions about transforming XML with XSLT and FOP.
javauser007
Posts: 6
Joined: Tue Oct 22, 2019 12:53 pm

Breaking for-each loop on a conditional base

Post by javauser007 » Wed Oct 30, 2019 5:17 pm

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.

adrian
Posts: 2614
Joined: Tue May 17, 2005 4:01 pm

Re: Breaking for-each loop on a conditional base

Post by adrian » Wed Oct 30, 2019 7:44 pm

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
Adrian Buza
<oXygen/> XML Editor, Schema Editor and XSLT Editor/Debugger
http://www.oxygenxml.com

javauser007
Posts: 6
Joined: Tue Oct 22, 2019 12:53 pm

Re: Breaking for-each loop on a conditional base

Post by javauser007 » Thu Oct 31, 2019 8:41 am

Thanks Adrian, this helped me.

Post Reply