<while>

While loop processor

Core v2.2.0

Overview

The processor executes its body content repeatedly as long as the specified condition evaluates to true. Unlike , which iterates over a collection, continues until a condition becomes false or maxloops limit is reached.

Usage Examples

Example 1: Pagination with has-next indicator

example-1.xml
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns="http://org.webharvest/schema/2.1/core">
<def var="hasNextPage" value="true"/>
<def var="page" value="1"/>

<while condition="${hasNextPage}" maxloops="20">
  <def var="response">
    <http url="https://api.example.com/products?page=${page}"/>
  </def>
  
  <!-- Check if there's a next page -->
  <def var="hasNextPage">
    <xpath expression="//pagination/hasNext/text()">
      <json-to-xml>${response}</json-to-xml>
    </xpath>
  </def>
  
  <!-- Increment page -->
  <def var="page">
    <script>parseInt(context.getVar("page")) + 1</script>
  </def>
</while>
</config>

Example 2: Retry logic with backoff

example-2.xml
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns="http://org.webharvest/schema/2.1/core">
<def var="success" value="false"/>
<def var="retryCount" value="0"/>

<while condition="${!success && retryCount < 3}" maxloops="3">
  <def var="response">
    <http url="https://api.example.com/data"/>
  </def>
  
  <if condition="${!empty(response)}">
    <def var="success" value="true"/>
  </if>
  <else>
    <def var="retryCount">
      <script>parseInt(context.getVar("retryCount")) + 1</script>
    </def>
    <sleep time="1000"/>  <!-- Wait before retry -->
  </else>
</while>
</config>

Example 3: Process until specific value found

example-3.xml
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns="http://org.webharvest/schema/2.1/core">
<def var="found" value="false"/>

<while condition="${!found}" maxloops="50" index="i">
  <def var="item">
    <http url="https://api.example.com/item/${i}"/>
  </def>
  
  <if condition="${item == 'TARGET'}">
    <def var="found" value="true"/>
  </if>
</while>
</config>

Example 4: Dynamic pagination (unknown page count)

example-4.xml
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns="http://org.webharvest/schema/2.1/core">
<def var="hasMore" value="true"/>
<def var="offset" value="0"/>

<while test="${hasMore}" maxloops="100">
  <def var="data">
    <http url="https://api.example.com/items?offset=${offset}&limit=100"/>
  </def>
  
  <!-- Check if response has items -->
  <def var="itemCount">
    <xpath expression="count(//item)">
      <json-to-xml>${data}</json-to-xml>
    </xpath>
  </def>
  
  <if condition="${itemCount == '0'}">
    <def var="hasMore" value="false"/>
  </if>
  <else>
    <def var="offset">
      <script>parseInt(context.getVar("offset")) + 100</script>
    </def>
  </else>
</while>
</config>

Parameters

Important Notes

Related Processors