# XML to JSON and CSV Converter: Files, Feeds, Datasets (`ucchiii/xml-to-json`) Actor

Convert XML files, feeds or pasted XML to JSON and CSV. One dataset row per record via a record path, attributes, namespaces, force-list and flatten-to-dot-keys for CSV. Safe parsing (no external entities). Empty input = free demo.

- **URL**: https://apify.com/ucchiii/xml-to-json.md
- **Developed by:** [Actor Factory](https://apify.com/ucchiii) (community)
- **Categories:** Developer tools, Automation, Integrations
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.05 / 1,000 converted documents

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

**XML to JSON and CSV converter: one dataset row per record, from XML files, feeds or pasted text.**

If you have product feeds, RSS and Atom files, `pom.xml` files, SOAP or API responses, or exports from old systems in XML and you need rows for a spreadsheet, database or script, this Actor does the parsing for you. Give it XML file URLs and/or paste XML, name the element that repeats (the **record path**, like `catalog/product`), and every record comes back as one row. Attributes, namespaces, single-versus-repeated elements and nested values are handled with options you control. You pay per converted document, with no monthly rent.

**Try it free:** clear the input and press **Start**. A built-in sample product catalog is converted (not charged; rows carry `_demo: true`).

### What you get

Input XML:

```xml
<catalog>
  <product id="p-100"><name>USB-C cable</name><price currency="USD">9.90</price></product>
  <product id="p-101"><name>Desk lamp</name><price currency="USD">24.50</price></product>
</catalog>
```

With record path `catalog/product` and **Flatten to dot keys** on, you get two rows:

| @id | name | price.@currency | price.#text |
|---|---|---|---|
| p-100 | USB-C cable | USD | 9.90 |
| p-101 | Desk lamp | USD | 24.50 |

- **One dataset row per record** (or one row per document if no record path). Each row also carries `_source`, `_document` and `_record`.
- **JSON and CSV files** in the run's key-value store: all records of each input, plus `combined.json` / `combined.csv` when you give several inputs.
- **Error rows** for malformed XML with the 1-based **line** and **column**. They are free.

### How to use

1. **XML text** (paste it) and/or **XML file URLs** (public http(s) links, feeds included). Up to 100 inputs per run.
2. **Record path**: the repeating element, e.g. `catalog/product` or `rss/channel/item`. A simple XPath like `//item[@type='a']` also works. Empty = one row per document.
3. Optional: **attribute prefix** (default `@`), **text key** (default `#text`), **namespaces** (strip or keep), **always a list** (element names that must be arrays even when they occur once), **flatten to dot keys** for CSV, **convert numbers and booleans**, **output files**, **formula-safe CSV**, **max records**.

```json
{
  "fileUrls": ["https://example.com/feed/products.xml"],
  "recordPath": "rss/channel/item",
  "forceList": ["category"],
  "flatten": true
}
```

### Output details

- **Attributes** become keys with the prefix (`@currency`). An element with attributes or children and text keeps the text under the text key.
- **Repeated elements** become lists; use **Always a list** so a record with one `<tag>` has the same shape as one with three.
- **Namespaces**: stripped by default (`dc:title` becomes `title`). With keep, prefixes stay in names and `xmlns` declarations appear as attributes.
- **Values stay text** unless you turn on number and boolean conversion (this keeps leading zeros and long IDs safe).
- **Flatten**: `a.b.0.c` keys, so CSV columns are real columns. Without it, nested values are JSON text in CSV cells.
- **CSV**: columns are the union of keys in first-seen order. With formula-safe on, text starting with `=`, `+`, `@` (or `-` when not a number) gets an apostrophe so spreadsheets never run it as a formula.
- Comments and processing instructions are dropped. Mixed text around child elements is joined with spaces.
- **Encoding**: files are read using the encoding in their XML declaration (UTF-8, UTF-16, ISO-8859-1 and so on).

### Safety and limits (cannot be raised by input)

- XML is parsed with lxml in a locked-down mode: no external entities, no network access, no DTD loading. Any `<!ENTITY ...>` declaration is refused with an error row, so XXE and "billion laughs" files cannot do anything.
- **100 inputs** per run, **10 MB** per input, **100,000 records** per input, output files up to 50 MB.
- Public files only, no login. Links to internal network addresses are blocked.

### Pricing

Pay per event: **$0.0015 per converted document** ($1.50 per 1,000), however many records the document holds. Parse errors, failed downloads, inputs over a limit and the demo are free.
Store discounts apply automatically: BRONZE -10%, SILVER -20%, GOLD -30%.
If the maximum charge you set for the run is used up, remaining inputs get a free error row instead.

### FAQ

**Is it an XML validator or parser?** It checks that the XML is well-formed (errors come with line and column). It does not validate against an XSD.

**Can it handle huge files?** Up to 10 MB per input. Split larger files, or use a narrower record path and max records.

**Can I call it from code?** Yes, through the Apify API: send `{"xml": "...", "recordPath": "..."}` and read the dataset items.

If this Actor saved you time, a rating on the Store helps others find it.

### More tools from the same developer

- [YAML to JSON Converter](https://apify.com/ucchiii/yaml-json-converter) — YAML to JSON and JSON to YAML from text or files, with syntax errors by line and column
- [Flatten JSON to CSV](https://apify.com/ucchiii/flatten-json) — flatten nested JSON into flat rows with the separator you choose
- [JSON to CSV Converter](https://apify.com/ucchiii/json-to-csv) — turn nested JSON files or datasets into one flat CSV file
- [CSV to Excel Converter](https://apify.com/ucchiii/csv-xlsx-converter) — convert CSV, TSV, Excel XLSX, JSON and NDJSON files or Apify datasets into each other

# Actor input Schema

## `xml` (type: `string`):

Paste XML here (up to 10 MB). Leave this and the file URLs empty for a free demo with a built-in sample.

## `fileUrls` (type: `array`):

Public http(s) links to XML files or feeds (.xml, RSS, Atom, product feeds), up to 10 MB each and 100 per run. Each file counts as one document.

## `recordPath` (type: `string`):

Element path that repeats once per record, e.g. catalog/product or project/dependencies/dependency. Each match becomes one dataset row. A simple XPath such as //item\[@type='a'] also works. Leave empty for one row per document.

## `attributePrefix` (type: `string`):

Text put before attribute names in the JSON keys, so <price currency="USD"> becomes @currency. Use an empty value to drop the prefix.

## `textKey` (type: `string`):

Key that holds the text of an element that also has attributes or child elements, e.g. {"@currency": "USD", "#text": "9.90"}.

## `namespaces` (type: `string`):

Strip removes namespace prefixes so keys are plain names. Keep leaves prefixes like dc:title in the keys and adds the xmlns declarations.

## `forceList` (type: `array`):

Element names that must always come out as a list, even when they occur once, e.g. tag or item. Keeps the JSON shape the same from record to record.

## `flatten` (type: `boolean`):

Turn nested values into one flat row with keys like price.@currency and tags.tag.0. Off keeps nested JSON and puts nested values as JSON text in CSV cells.

## `parseValues` (type: `boolean`):

Turn text such as 9.90, 42 and true into real numbers and booleans in the JSON. Off keeps every value as text, which preserves leading zeros and long IDs.

## `outputFiles` (type: `string`):

Files saved in the key-value store: one JSON and/or CSV per input (all records), plus combined.json / combined.csv when several inputs are given.

## `formulaSafe` (type: `boolean`):

Puts an apostrophe before text that starts with = + @ (or - when it is not a number), so Excel and Google Sheets never run it as a formula.

## `jsonIndent` (type: `integer`):

Spaces per level in the JSON file. 0 = minified on one line.

## `maxRecords` (type: `integer`):

Stop after this many records per document. 0 = all (hard limit 100,000).

## Actor input object example

```json
{
  "fileUrls": [
    "https://raw.githubusercontent.com/spring-projects/spring-petclinic/main/pom.xml"
  ],
  "recordPath": "project/dependencies/dependency",
  "attributePrefix": "@",
  "textKey": "#text",
  "namespaces": "strip",
  "flatten": false,
  "parseValues": false,
  "outputFiles": "both",
  "formulaSafe": true,
  "jsonIndent": 2,
  "maxRecords": 0
}
```

# Actor output Schema

## `results` (type: `string`):

One item per record (or per document without a record path), or an error row with line and column.

## `files` (type: `string`):

The key-value store that holds the .json and .csv files.

## `stats` (type: `string`):

Record STATS: documents converted and failed, records, charged documents and file links.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "fileUrls": [
        "https://raw.githubusercontent.com/spring-projects/spring-petclinic/main/pom.xml"
    ],
    "recordPath": "project/dependencies/dependency"
};

// Run the Actor and wait for it to finish
const run = await client.actor("ucchiii/xml-to-json").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "fileUrls": ["https://raw.githubusercontent.com/spring-projects/spring-petclinic/main/pom.xml"],
    "recordPath": "project/dependencies/dependency",
}

# Run the Actor and wait for it to finish
run = client.actor("ucchiii/xml-to-json").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "fileUrls": [
    "https://raw.githubusercontent.com/spring-projects/spring-petclinic/main/pom.xml"
  ],
  "recordPath": "project/dependencies/dependency"
}' |
apify call ucchiii/xml-to-json --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,ucchiii/xml-to-json"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/NoJd5hiDL8CrTmVrj/builds/rpHs4Mq9TarhYJoAL/openapi.json
