While loop processor
Core v2.2.0
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.
<?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>
<?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>
<?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>
<?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>