<xml-to-json>

XML to JSON converter

Core v2.2.0

Overview

The processor converts XML data into JSON format. This is useful when you need to send scraped data to REST APIs, JavaScript applications, or any system that expects JSON input. It's the reverse operation of .

Usage Examples

Example 1: Convert extracted data to JSON

example-1.xml
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns="http://org.webharvest/schema/2.1/core">
<!-- Extract product data as XML -->
<def var="productXml">
  <xpath expression="//div[@class='product']">
    <html-to-xml>
      <http url="https://example.com/products"/>
    </html-to-xml>
  </xpath>
</def>

<!-- Convert to JSON -->
<def var="productJson">
  <xml-to-json>${productXml}</xml-to-json>
</def>

<!-- Save as JSON file -->
<file path="products.json" action="write">
  ${productJson}
</file>
</config>

Example 2: POST JSON to API

example-2.xml
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns="http://org.webharvest/schema/2.1/core">
<!-- Build XML structure -->
<def var="userData">
  <template>
    <![CDATA[
    <user>
      <name>John Doe</name>
      <email>john@example.com</email>
      <age>30</age>
    </user>
    ]]>
  </template>
</def>

<!-- Convert to JSON -->
<def var="userJson">
  <xml-to-json>${userData}</xml-to-json>
</def>

<!-- POST to API -->
<http url="https://api.example.com/users" method="POST">
  <http-header name="Content-Type">application/json</http-header>
  <template>${userJson}</template>
</http>
</config>

Example 3: Scrape HTML → Export JSON

example-3.xml
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns="http://org.webharvest/schema/2.1/core">
<!-- Scrape product list -->
<def var="products">
  <xpath expression="//div[@class='product']">
    <html-to-xml>
      <http url="https://example.com/products"/>
    </html-to-xml>
  </xpath>
</def>

<!-- Build XML structure -->
<def var="productsXml">
  <template>
    <![CDATA[<products>]]>
  </template>
</def>

<loop item="product">
  ${products}
  
  <def var="name"><xpath expression=".//h3/text()">${product}</xpath></def>
  <def var="price"><xpath expression=".//span[@class='price']/text()">${product}</xpath></def>
  
  <def var="productsXml" value="${productsXml}">
    <template>
      <![CDATA[
      <product>
        <name>${name}</name>
        <price>${price}</price>
      </product>
      ]]>
    </template>
  </def>
</loop>

<def var="productsXml" value="${productsXml}</products>"/>

<!-- Convert entire structure to JSON -->
<def var="productsJson">
  <xml-to-json>${productsXml}</xml-to-json>
</def>

<file path="products.json" action="write">
  ${productsJson}
</file>
</config>

Important Notes

Related Processors