<if>

Conditional execution processor

Core v2.2.0

Overview

The processor evaluates a boolean condition and executes its body content only when the condition is true. It's essential for implementing conditional logic, error handling, data validation, and dynamic behavior in scrapers.

Usage Examples

Example 1: Basic conditional execution

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

<if condition="${httpStatus == '200'}">
  <file path="success.log" action="append">
    Request succeeded at ${_date}
  </file>
</if>
</config>

Example 2: Error handling

example-2.xml
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns="http://org.webharvest/schema/2.1/core">
<def var="response">
  <http url="https://api.example.com/data"/>
</def>

<if condition="${empty(response)}">
  <file path="errors.log" action="append">
    Failed to fetch data from API
  </file>
  <exit/>
</if>

<!-- Continue with non-empty response -->
</config>

Example 3: If-else pattern with {@code }

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

<if condition="${stock > 0}">
  <def var="status" value="In Stock"/>
</if>
<else>
  <def var="status" value="Out of Stock"/>
</else>
</config>

Example 4: Numeric comparison

example-4.xml
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns="http://org.webharvest/schema/2.1/core">
<loop item="product" index="i" maxloops="100">
  <xpath expression="//product">...</xpath>
  
  <def var="price">
    <xpath expression=".//price/text()">${product}</xpath>
  </def>
  
  <!-- Only save expensive products -->
  <if condition="${price > 100}">
    <file path="expensive-products.txt" action="append">
      Product ${i}: $${price}
    </file>
  </if>
</loop>
</config>

Example 5: String matching

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

<if condition="${category == 'electronics'}">
  <http url="https://example.com/electronics"/>
</if>
</config>

Example 6: Variable existence check

example-6.xml
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns="http://org.webharvest/schema/2.1/core">
<if condition="${empty(apiKey)}">
  <def var="apiKey" value="default-key"/>
</if>

<http url="https://api.example.com?key=${apiKey}"/>
</config>

Important Notes

Related Processors