XSLT: How to exit a "for-each" loop if a condition is satisfied

12,615

How do I exit a "for-each" loop in XSL if a condition is satisfied?

This is not possible. There isn't any XSLT instruction for exiting the processing of xsl:for-each and continuing the execution of the transformation. What you can do is specify precisely the conditions that the selected nodes should meet.

Use:

<xsl:for-each select=
 "/*/apartment
      [apartment_details[bedrooms=$bedrooms and $budget  >= rent]]">
  <!-- output apartment address here -->  
</xsl:for-each>

This code displays the address of any apartment that is a child of the top element of the XML document and that has an apartment_details child, for whose children bedrooms and rent it is true() that: bedrooms=$bedrooms and $budget >= rent

Share:
12,615
earthling
Author by

earthling

Updated on June 05, 2022

Comments

  • earthling
    earthling almost 2 years

    How do I exit a "for-each" loop in XSL if a condition is satisfied? e.g. Suppose I want the XSL to display the address of apartments which have (2 bedrooms and rent <= 1000), in the following XML, the following XSL code:

    <xsl:for-each select="//apartment/apartment_details">
      <xsl:if test="bedrooms=$bedrooms and rent &lt;= $budget "> 
        <!--display apartment address--> 
      </xsl:if>
    </xsl:for-each>
    

    would return the same apartment address twice. I want to display the apartment address only once even if there are multiple for the apartment that satisfy the condition.

    XML structure:

    <apartments>
      <apartment>
        <address>
            <street>....</street>
            <city>....</city>
        </address>
        <apartment_details>
            <bedrooms>2</bedrooms>
            <bathrooms>2</bathrooms>
            <rent>1000</rent>
        </apartment_details>
        <apartment_details>
            <bedrooms>2</bedrooms>
            <bathrooms>1</bathrooms>
            <rent>900</rent>
        </apartment_details>
        ...
      </apartment>
      ...
    </apartments>
    

    Thank you.