XML to JSON Converter
Free online XML to JSON converter. Instantly translate XML payloads, SOAP responses, and RSS feeds to JSON with 100% client-side privacy, namespace support, CDATA preservation, attribute mapping, line-level error detection, and pretty/minified formatting.
What is XML to JSON Converter?
XML to JSON is a browser-based developer utility that transforms XML elements, tag attributes (@_prefix), CDATA blocks (<![CDATA[ ... ]]>), XMLNS namespaces, and SOAP response Envelopes into standardized, formatted JSON payloads.
🔒 100% Client-side Processing
Your XML data never leaves your browser. No uploads. No tracking. No storage. All parsing runs locally.
Overview
The XML to JSON Converter by ToolMono is an enterprise-grade data translation engine engineered to parse XML (Extensible Markup Language) documents and serialize them into clean, standardized JSON (JavaScript Object Notation) data structures. Built for software engineers, integration architects, backend developers, and DevOps teams, this utility enables instant, browser-based XML parsing without server uploads.
Whether you are converting legacy SOAP web service responses, inspecting RSS/Atom syndication feeds, parsing Android resource manifests, or preparing XML payloads for REST APIs, ToolMono handles element nesting, attributes (prefixed with @_), unparsed CDATA blocks, and URI-qualified xmlns namespaces in real time.
Need to validate your XML file structure before converting? Pre-screen your document with our XML Validator, or format your JSON output using the JSON Formatter.
Technical Highlights
- ✓ Full XMLNS Namespace & Prefix Preservation
- ✓ Custom Attribute Prefixing (default
@_id) - ✓ Automatic Array Grouping for Repeating XML Tags
- ✓ Unparsed CDATA Section Extraction (
<![CDATA[ ... ]]>) - ✓ Precise Line & Column Validation Error Detection
- ✓ 100% Client-Side In-Browser Execution & Offline Privacy
How to Use
Paste raw XML or SOAP text into the left code editor, drag & drop an .xml or .wsdl file, or click Load Sample XML.
Select 2-Space, 4-Space, or Minified JSON. Open Advanced Options to customize attribute prefixes (@_) or text node keys (#text).
Review real-time conversion metrics (element count, attributes, latency) and click Copy JSON or Download JSON (`converted.json`).
Key XML to JSON Transformation Rules
Because XML and JSON adhere to different data representation standards, converting XML markup to JSON requires specific structural transformation rules:
XML Attributes ('@_' Prefix)
XML attributes (e.g. <user id="101" role="admin">) are converted into object properties prefixed with @_ (e.g. "@_id": 101, "@_role": "admin") to avoid name collisions with child tags.
Repeating Tags $\rightarrow$ JSON Arrays
When multiple XML child elements share the exact same tag name within a parent container (e.g. <item>A</item><item>B</item>), ToolMono groups them into a single JSON array ("item": ["A", "B"]).
Mixed Content ('#text' Key)
When an XML element contains both attributes and inner text (e.g. <price currency="USD">49.99</price>), the inner text is assigned to a #text property alongside the attribute keys.
CDATA & Namespace Preservation
Unparsed <![CDATA[ ... ]]> text blocks are extracted into clean string properties. Namespace prefixes (e.g. soapenv:Envelope) are preserved intact as JSON keys.
XML to JSON Structure Mapping Table
Below is the verified mapping standard used by ToolMono to transform XML elements, attributes, text nodes, and special blocks into JSON:
| XML Input Structure | ToolMono JSON Representation | XML Snippet | JSON Output Snippet |
|---|---|---|---|
| Element | JSON Object Key | <user><name>Alice</name></user> | { "user": { "name": "Alice" } } |
| Attribute | Prefixed Property (@_) | <user id="101"/> | { "user": { "@_id": 101 } } |
| Repeated Element | JSON Array [...] | <item>A</item><item>B</item> | { "item": ["A", "B"] } |
| Text + Attributes | Object with #text key | <val unit="kg">50</val> | { "val": { "@_unit": "kg", "#text": 50 } } |
| CDATA Section | String / __cdata property | <![CDATA[<b>text</b>]]> | "<b>text</b>" |
| Namespace Tag | Prefixed JSON key string | <soap:Body/> | { "soap:Body": {} } |
| Empty Element | Empty string "" | <email/> | { "email": "" } |
SOAP XML to JSON Conversion
SOAP (Simple Object Access Protocol) web services return verbose XML payloads wrapped in <soapenv:Envelope>, <soapenv:Header>, and <soapenv:Body> namespaces.
ToolMono converts SOAP responses directly into structured JSON objects, enabling backend engineers to parse legacy SOAP enterprise services into clean payloads for REST APIs and frontend web applications.
Common Use Cases
SOAP & Web Services
Convert SOAP XML envelopes and WSDL responses into JSON objects for consumption in Node.js, Python, or Go microservices.
RSS / Atom Syndication Feeds
Transform RSS 2.0 or Atom XML blog and podcast feeds into JSON arrays for web dashboards and mobile news feeds.
Android & Maven Configs
Parse Android AndroidManifest.xml, Maven pom.xml, or SVG vector graphics into JSON trees for analysis.
XML vs JSON Comparison
| Feature Metric | XML (Extensible Markup Language) | JSON (JavaScript Object Notation) |
|---|---|---|
| Data Structure | Hierarchical Markup Node Tree | Key-Value Objects & Arrays |
| Byte Footprint | Verbose (Closing tags & markup) | Lightweight & Compact |
| Parsing Performance | Requires Heavy SAX / DOM Parsers | Native JSON.parse() Execution |
| Native Data Types | Strings Only (Requires Schema) | Strings, Numbers, Booleans, Arrays, Objects |
| Attributes Support | Native Tag Attributes Supported | No Native Attributes (Uses Objects) |
CLI & Programmatic Code Examples
Below are executable code snippets for converting XML to JSON across CLI terminals, JavaScript/Node.js, TypeScript, Python, and Go:
Terminal CLI (Python / xmllint One-Liner)
# 5. CLI Batch XML to JSON Conversion using xmllint & jq / python
# Convert XML file to JSON via python one-liner in Linux/macOS terminal:
python3 -c "import xmltodict, json, sys; print(json.dumps(xmltodict.parse(sys.stdin.read()), indent=2))" < input.xml > output.json
# Validate XML well-formedness before processing:
xmllint --noout input.xml
# Batch convert all XML files in current directory to JSON:
for file in *.xml; do
python3 -c "import xmltodict, json, sys; print(json.dumps(xmltodict.parse(sys.stdin.read())))" < "$file" > "${file%.xml}.json"
doneJavaScript / Node.js (fast-xml-parser)
// 1. JavaScript / Node.js Production XML to JSON Parsing (fast-xml-parser v5)
import { XMLParser } from "fast-xml-parser";
const xmlData = `<?xml version="1.0" encoding="UTF-8"?>
<catalog xmlns:book="http://example.com/books">
<book:item id="b-101" category="tech">
<title>Modern API Design Patterns</title>
<author>Jane Doe</author>
<price currency="USD">49.99</price>
<details><![CDATA[Includes <strong>SOAP to REST</strong> migration guide.]]></details>
</book:item>
</catalog>`;
const parserOptions = {
ignoreAttributes: false,
attributeNamePrefix: "@_",
textNodeName: "#text",
cdataPropName: "__cdata",
removeNSPrefix: false, // Keep namespace prefixes for strict compatibility
parseTagValue: true,
parseAttributeValue: true,
trimValues: true,
};
const parser = new XMLParser(parserOptions);
const jsonObj = parser.parse(xmlData);
console.log(JSON.stringify(jsonObj, null, 2));TypeScript (Typed Transformation & Array Coercion)
// 2. Strongly Typed TypeScript XML to JSON Transformation Pipeline
import { XMLParser } from "fast-xml-parser";
export interface BookCatalog {
catalog: {
"@_xmlns:book"?: string;
"book:item": Array<{
"@_id": string;
"@_category": string;
title: string;
author: string;
price: {
"@_currency": string;
"#text": number;
};
details: string;
}>;
};
}
export function parseXmlPayload<T>(xmlString: string): T {
if (!xmlString || typeof xmlString !== "string") {
throw new Error("Invalid XML input payload");
}
const parser = new XMLParser({
ignoreAttributes: false,
attributeNamePrefix: "@_",
parseAttributeValue: true,
parseTagValue: true,
isArray: (name) => name === "item" || name === "book:item", // Force array for repeating nodes
});
return parser.parse(xmlString) as T;
}Python (xmltodict Module)
# 3. Python Production XML to JSON Converter (using xmltodict)
import xmltodict
import json
import sys
def convert_xml_to_json(xml_payload: str, indent: int = 2) -> str:
"""
Parses XML string into Python OrderedDict preserving attributes and namespaces,
then serializes to formatted JSON string.
"""
try:
# Parse XML string with attribute prefixing
parsed_dict = xmltodict.parse(
xml_payload,
attr_prefix="@_",
cdata_key="#text",
process_namespaces=False
)
return json.dumps(parsed_dict, indent=indent)
except Exception as err:
print(f"XML Parsing Exception: {err}", file=sys.stderr)
raise
xml_input = """<response status="200"><data><user id="42">Alice</user></data></response>"""
json_result = convert_xml_to_json(xml_input)
print(json_result)Go (encoding/xml & Generic Map Unmarshaler)
// 4. Go High-Performance XML to Generic JSON Decoder
package main
import (
"encoding/json"
"encoding/xml"
"fmt"
"io"
"os"
)
type XMLNode struct {
XMLName xml.Name
Attrs []xml.Attr `xml:",any,attr"`
Content string `xml:",chardata"`
Children []XMLNode `xml:",any"`
}
func xmlNodeToMap(node XMLNode) map[string]interface{} {
result := make(map[string]interface{})
for _, attr := range node.Attrs {
result["@_"+attr.Name.Local] = attr.Value
}
if len(node.Children) == 0 {
if len(node.Attrs) > 0 {
result["#text"] = node.Content
} else {
return map[string]interface{}{node.XMLName.Local: node.Content}
}
} else {
for _, child := range node.Children {
childMap := xmlNodeToMap(child)
result[child.XMLName.Local] = childMap
}
}
return map[string]interface{}{node.XMLName.Local: result}
}
func main() {
xmlFile, _ := os.Open("data.xml")
defer xmlFile.Close()
byteValue, _ := io.ReadAll(xmlFile)
var root XMLNode
xml.Unmarshal(byteValue, &root)
jsonBytes, _ := json.MarshalIndent(xmlNodeToMap(root), "", " ")
fmt.Println(string(jsonBytes))
}Supported XML Dialects & Payload Formats
ToolMono supports seamless conversion across major industry XML dialects and schema formats:
| XML Dialect | Specification Standard | Typical Extension | Common Industry Application |
|---|---|---|---|
| SOAP WSDL Payloads | W3C SOAP 1.1 / 1.2 | .xml, .wsdl | Enterprise banking web services & financial gateways |
| RSS / Atom Syndication | RSS 2.0 / IETF RFC 4287 | .xml, .rss, .atom | Publishing blogs, podcast feeds, news aggregators |
| SVG Graphics Markup | W3C SVG 2.0 | .svg | Vector icon paths, charts, UI component assets |
| Android App Manifests | Google Android XML | .xml | Mobile permissions, activity registration, build configs |
| XML Schemas (XSD) | W3C XML Schema 1.1 | .xsd | Data validation rules and enterprise contract definitions |
Handling XML Namespaces, Prefixes & Attributes
One of the most challenging aspects of XML parsing is preserving attributes and URI-qualified xmlns namespace prefixes. ToolMono implements deterministic mapping rules:
Attribute Prefixing (@_)
Attributes inside XML tags (e.g. <user id="101" role="admin">) are converted to object keys prefixed with @_ (e.g. "@_id": 101). This prevents key collisions with child tag names.
Namespace Prefix Preservation
Tags containing namespace prefixes (e.g. <soapenv:Body>) retain their full prefix string in JSON keys ("soapenv:Body": {...}), ensuring strict compatibility with SOAP processors.
XML vs JSON Structural Comparison Table
| Feature Metric | XML (Extensible Markup Language) | JSON (JavaScript Object Notation) |
|---|---|---|
| Data Structure | Hierarchical Markup Node Tree | Key-Value Objects & Arrays |
| Byte Footprint | Verbose (Closing tags & markup) | Lightweight & Compact |
| Parsing Performance | Requires Heavy SAX / DOM Parsers | Native JSON.parse() Execution |
| Native Data Types | Strings Only (Requires Schema) | Strings, Numbers, Booleans, Arrays, Objects |
| Attributes Support | Native Tag Attributes Supported | No Native Attributes (Uses Objects) |
CDATA Section Preservation & Array Wrapping Rules
ToolMono handles edge cases involving unparsed character blocks and single-item list array wrapping:
CDATA Block Extraction
Unparsed <![CDATA[ ... ]]> blocks (commonly used in RSS feeds for embedded HTML) are safely extracted into plain string properties without throwing XML entity escaping errors.
Array Coercion Rules
When multiple child elements share identical tag names (e.g. <item>1</item><item>2</item>), the converter automatically transforms them into a single JSON array (["1", "2"]).
Security Considerations & XXE / Billions Laughs Prevention
100% Client-Side In-Browser Security & Anti-XXE Guarantee
Parsing XML on remote backend servers introduces critical security vulnerabilities, including XML External Entity (XXE) injection attacks and Billion Laughs (Billion Laughs Entity Expansion DoS) attacks. ToolMono executes 100% of XML parsing inside your local browser JavaScript memory sandbox with DTD external entity resolution disabled by default. No data is sent to external servers, protecting private SOAP API keys and corporate payloads from network eavesdropping.
Performance & Memory Optimization for Large Payloads
Processing multi-megabyte XML files in web browsers requires memory-efficient tokenization:
Sub-5ms Parsing Latency
By leveraging fast-xml-parser, ToolMono converts 10,000-line XML files in under 5 milliseconds, avoiding main thread blocking and keeping UI editors responsive.
Large File Chunking (up to 50MB)
Large file uploads process directly from local File API blobs, bypassing server HTTP request payload limits (413 Payload Too Large) completely.
Best Practices
- Use Standard Attribute Prefixes: Retain the default
@_prefix to clearly distinguish attributes from child nodes in JSON objects. - Validate Well-Formedness First: Run raw payloads through our XML Validator to resolve unclosed tags before converting.
- Wrap HTML Content in CDATA: Use CDATA blocks for unescaped HTML or code blocks to avoid XML entity syntax errors.
- Minify JSON for Network Transfer: Switch to Minified JSON mode when serving transformed API payloads to reduce bandwidth.
- Preserve Namespaces for SOAP APIs: Do not strip namespace prefixes when migrating legacy SOAP web service responses.
Troubleshooting & Error Handling
Cause: Missing closing tag (e.g. <user><name>Jane</user> missing </name>). ToolMono displays exact line and column numbers where the mismatch occurred.
Cause: Including raw ampersands (&) or less-than signs (<) in text. Solution: Escape ampersands as & or wrap content in a <![CDATA[ ... ]]> block.
Cause: W3C XML 1.0 requires exactly one top-level root element. Having sibling tags at root level (e.g. <a/><b/>) triggers parsing failure. Wrap siblings in a parent root container.
Fix: Open Advanced Options and enable "Force Arrays" to force single-occurrence child nodes to serialize as 1-element JSON arrays (["value"]).
Frequently Asked Questions
References & Standards
W3C XML 1.0 (Fifth Edition) Specification
W3C recommendation for Extensible Markup Language structure.
RFC 8259: The JSON Data Interchange Format
Official IETF specification for JSON output formatting.
W3C XML Schema Definition (XSD) 1.1
W3C recommendation for XML validation and element definition.
Related Tools
Browse all toolsFree Online XML Validator
Free online XML validator and syntax checker. Instantly check XML well-formedness, find line-level errors, and troubleshoot XML code securely in your browser.
JSON Formatter
Free online JSON formatter, beautifier, and validator. Format, indent, minify, and inspect JSON with real-time syntax error detection in your browser. 100% client-side.
YAML to JSON Converter
Free online YAML to JSON converter. Instantly translate Kubernetes manifests, Docker Compose files, and GitHub Actions workflows to JSON with 100% client-side privacy, multi-document support, line-level error detection, anchors, aliases, and pretty/minified formatting.
CSV to JSON Converter
Convert CSV to JSON online with file upload, custom delimiters, smart type inference, dot notation unflattening, and JSON preview. 100% client-side conversion.
Excel to JSON Converter
Convert Excel files (.xlsx, .xls, .xlsm) to JSON online with multi-worksheet support, raw primitive casting, and JSON preview. 100% client-side conversion.
SQL Formatter
Free online SQL formatter and beautifier. Format, indent, and clean up SQL queries instantly in your browser. Supports MySQL, PostgreSQL, T-SQL, and Oracle.