earthling
earthling

Reputation: 53

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

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.

Upvotes: 3

Views: 13886

Answers (2)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243599

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

Upvotes: 4

luke2012
luke2012

Reputation: 1734

I don't think you would need to use a loop, instead try a filter expression:

<xsl:value-of select="NODE[CRITERIA][1]">

Upvotes: 0

Related Questions