XML to JSON

Free online XML to JSON converter powered by the browser DOMParser. XML attributes map directly to fields, repeated elements merge into arrays, element text goes into a value field. Output to JSON or YAML with prettyPrint and XML error self-repair, 100% in your browser.

Related

About XML to JSON: convert XML data into standard JSON objects automatically

XML to JSON is the process of converting XML-formatted data (SOAP messages, RSS feeds, configuration files) into JSON objects. XML is the traditional format for enterprise systems, SOAP Web Services, configuration files, and Office documents, while JSON is the de-facto standard for modern Web APIs, JavaScript, and NoSQL databases. Each format has its strengths: XML is strict, self-describing, and widely supports namespaces and schema validation; JSON is concise, easy to parse, and naturally fits JavaScript. Converting XML to JSON for modern frontends or microservices is a common need, and this tool automates that process.

The tool's core is using the browser's native DOMParser to parse XML and auto-traverse the DOM tree to produce a JSON object. DOMParser is the browser's built-in XML parser, follows the W3C DOM standard, and supports all XML 1.0 features including namespaces, CDATA, comments, and attributes. DOM-based parsing brings zero dependencies, good performance, and standard compliance.

The mapping rules are intuitive: each XML element becomes a JSON object, element attributes become object fields directly (no @ prefix, avoiding the messy naming conventions of some tools), element text goes into a value field, and repeated sibling elements with the same tag name are merged into arrays. For example <bookstore><book id="1"><title>Great Gatsby</title></book><book id="2"><title>Brief History</title></book></bookstore> becomes {bookstore: {book: [{id: "1", title: {value: "Great Gatsby"}}, {id: "2", title: {value: "Brief History"}}]}}.

The choice of attribute direct mapping without prefix is a key design decision. Many XML conversion tools use @attribute, #text and other special prefixes to distinguish attributes and text. While accurate, the resulting JSON structure is awkward and hard to consume in JavaScript directly. Direct attribute mapping makes the generated JSON closer to real business data models; developers can define matching types in a TypeScript interface directly.

Array-ification of repeated elements is another key design. XML has no native array concept, requiring repeated elements (e.g. multiple <item>) to represent list data. The tool automatically detects multiple sibling elements with the same tag name and merges them into arrays, aligning with JSON's list semantics and avoiding data loss or the need for manual merging.

Dual output format (JSON + YAML) is a differentiating design. YAML is another popular data serialization format, widely used in Kubernetes, Docker Compose, Ansible, and GitHub Actions configurations. The tool includes a simple YAML converter that supports standard 2-space indentation, list prefix -, and key:value syntax. Toggle between JSON/YAML with one click.

XML error self-repair (tryFixXML) improves the tool's fault tolerance. Real-world XML input often lacks the XML declaration (<?xml version="1.0"?>) or uses HTML-style self-closing tags (e.g. <br>) rather than the XML-style <br />. The tool auto-adds the XML declaration and completes the trailing slash on self-closing tags, allowing the DOMParser to correctly process more non-standard XML.

XML formatting and compression (formatXML/compressXML) are powered by the xml-formatter library. The prettyPrint mode outputs 2-space indented, line-break-preserved readable XML; the compress mode outputs whitespace-stripped, single-line compact XML suitable for network transmission. Developers can use the tool to compress XML before storing in a database, saving 30-50% of storage space.

Real-time auto conversion is a practical feature. After typing stops, the tool converts with 500ms debounce; combined with the six keyboard shortcuts (macOS ⇧⌘+F/C/T/O/D/K), users can quickly complete common operations like format, compress, convert, upload, download, and clear without mouse clicks.

Pure client-side processing is the core architecture. All XML parsing, DOM traversal, JSON serialization, and YAML conversion run in browser JavaScript. DOMParser is provided natively by the browser (no need to bundle an XML parser), and xml-formatter is a lightweight npm package (under 30KB). Original XML data is never sent to a server, so sensitive SOAP messages (containing order information, user credentials, or enterprise API responses) can be processed safely locally.

Use Cases

  • Convert XML responses from payment gateways, ERP, or CRM legacy APIs into JSON for modern frontends or Node.js backends.
  • Parse RSS / Atom feeds into JSON for display on web frontends, aggregation into unified feed readers, or import into databases.
  • Read XML configuration files from Java applications (web.xml, applicationContext.xml) and convert to JSON for jq queries or other tools.
  • Convert SOAP 1.1/1.2 XML responses to JSON and process them with Node.js libraries like jsonwebtoken or lodash.
  • Parse Maven pom.xml, Ant build.xml and similar build scripts into JSON for project metadata visualization or dependency analysis.
  • Convert RSS feeds, Sitemap XML, and Atom subscription sources to JSON for storage in modern databases like Elasticsearch or MongoDB.
  • Convert industry-standard XML formats (HL7, ISO 20022) from healthcare or finance to JSON for modern microservices.
  • Convert SEO-related XML files (sitemap.xml, robots.xml) from Google Merchant Center or Sitemap.org to JSON for crawlers or analytics.

How to Use

  1. Paste your XML into the left editor, click the Upload button to select a .xml/.txt file, or click Sample to load the built-in bookstore example.
  2. The tool converts automatically 500ms after you stop typing. View the converted JSON or YAML on the right with CodeMirror syntax highlighting.
  3. Click the JSON / YAML buttons in the right toolbar to switch output format in real time. You can also use the Format (⇧⌘+F) or Compress (⇧⌘+C) buttons to adjust the XML input format.
  4. Click Copy to put the JSON/YAML on the clipboard, or click Download to save it as a file with the right extension (output.json / output.yaml / output.xml).
  5. To fix XML syntax errors, click the Fix button next to the error message. The tool calls tryFixXML to add the XML declaration and complete self-closing tags automatically.
  6. Paste the JSON into your target code (TypeScript interface definition, API response type, etc.) or import it into your backend service for further processing.

Features

  • Smart DOM tree parsing: parses XML with the browser's native DOMParser and auto-traverses the node tree to produce a standard JSON object, zero dependencies.
  • Direct attribute mapping: XML attributes (e.g. id="1", category="fiction") become regular JSON object fields without any @ prefix.
  • Repeated-element arrays: sibling elements with the same tag name are auto-merged into JSON arrays ({book: [{...}, {...}]}), matching common data structure conventions.
  • Text node extraction: element text content is auto-stored in a value field, alongside attributes and child elements.
  • Dual format output: one-click switch between JSON (2-space prettyPrint) and YAML (2-space indent, list prefix -) for different use cases.
  • XML error self-repair: built-in tryFixXML adds missing XML declarations and completes self-closing tags automatically.
  • XML format and compress: uses the xml-formatter library to support prettyPrint and minify output (2-space indent or no whitespace).
  • Real-time auto conversion: converts 500ms after you stop typing, with output updated live without manual clicking.
  • JSON/XML dual highlighting: the left side uses CodeMirror XML syntax highlighting; the right side switches between JSON and YAML highlighting.
  • Complete shortcut system: six common shortcuts (format/compress/convert/upload/download/clear) for macOS and Windows/Linux.
  • Copy and download: copy to the clipboard with one click, or download as output.json / output.yaml / output.xml (extension auto-selected by format).
  • 100% browser-side: all XML parsing, DOM traversal, and JSON serialization happen in client-side JavaScript; the original XML never leaves your device, and DOMParser is provided natively by the browser.

FAQ

How do I convert XML to JSON format?

Paste your XML into the left editor and the tool uses the browser's native DOMParser to parse it, then automatically traverses the DOM tree to build a standard JSON object. The root node is wrapped in { [tagName]: {...} }, attributes map directly to fields (no @ prefix), element text goes into a value field, and repeated sibling elements with the same tag name are merged into an array. Conversion runs 500ms after you stop typing.

How are XML attributes and text nodes mapped?

The tool uses an intuitive mapping: XML attributes become regular JSON object fields (e.g. <book id="1"> becomes {id: "1", ...} without any @ prefix), and element text content goes into a value field (e.g. <title>Great Gatsby</title> becomes {value: "Great Gatsby"}). When an element has both attributes and text, both are stored as siblings in the same object.

Are repeated XML elements automatically converted to JSON arrays?

Yes. The tool automatically detects multiple sibling elements with the same tag name (e.g. three <book> elements under <bookstore>) and merges them into a JSON array. For example <bookstore><book>...</book><book>...</book></bookstore> becomes {bookstore: {book: [{...}, {...}]}}. This convention matches the most common XML data structures.

How are pure text nodes handled?

When an XML element has no attributes and only text content, the tool returns the text directly as a string (e.g. <name>Alice</name> becomes "Alice"). When the element has both attributes and text, the attributes and the text are stored as siblings in the same object ({attr: "...", value: "..."}). When the element has child elements, child elements become object fields, and any text content is merged into a value field.

Can the tool handle malformed XML (missing closing tags)?

Yes. The tool's built-in tryFixXML repair function automatically adds the missing XML declaration (<?xml version="1.0" encoding="UTF-8"?>) and completes the trailing slash for self-closing tags like br, hr, and img. This significantly improves compatibility with legacy systems and non-standard third-party APIs.

Which XML file types are supported?

The tool supports .xml and .txt files (UTF-8 encoded). Click the Upload button to select a local file; the tool reads it through the browser's native FileReader API without uploading to a server. After upload, the content is automatically filled into the input box and triggers conversion.

Can it output both JSON and YAML?

Yes. The tool supports both JSON and YAML output. Click the JSON/YAML toggle in the right toolbar to switch formats in real time. JSON is output with 2-space prettyPrint; YAML uses standard 2-space indentation, list prefix -, and key:value syntax, suitable for Kubernetes, Docker Compose, and Ansible configurations.

What is the download filename?

The extension is chosen automatically based on the current output format: output.json for JSON, output.yaml for YAML, and output.xml (the original format) when there is input but no conversion. All files are UTF-8 encoded and can be read directly by their respective format parsers.

What keyboard shortcuts are available?

The tool supports these shortcuts: on macOS, ⇧⌘+F to format, ⇧⌘+C to compress, ⇧⌘+T to convert, ⇧⌘+O to upload, ⇧⌘+D to download, ⇧⌘+K to clear; on Windows/Linux, use Ctrl instead of ⌘. Six shortcuts cover the full workflow.

Are XML namespaces supported?

Yes. The tool uses DOMParser to parse XML, which natively supports namespaces (xmlns). Namespace prefixes are preserved as part of the element name in the JSON, e.g. <svg:circle> becomes {svg:circle: {...}}. To access cross-namespace elements, identify them by namespace prefix in the JSON parser.

Are CDATA sections supported?

Yes. CDATA section content (<![CDATA[...]]>) is automatically merged into the element's textContent by the DOMParser, and the tool extracts it into the value field just like normal text. However, because CDATA is an XML node type rather than a string, the original CDATA and normal text cannot be distinguished in the JSON output.

What input file size is supported?

There is no hard limit; the practical limit is browser memory. XML up to 1-2 MB works smoothly; larger files may slow down because of the DOMParser's higher memory footprint. If you experience lag with large SOAP messages or RSS feeds, consider trimming or splitting them in a local XML editor first.

Troubleshooting

JSON parse error 'unclosed token' - what to do?

The cause is usually XML missing closing tags, mismatched attribute quotes, or unescaped special characters. Click the Fix button next to the error to call tryFixXML, which auto-adds the XML declaration and completes self-closing tags. If it still fails, manually check the XML structure or use document.documentElement.outerHTML in browser dev tools to see the parsed result.

Attribute order in JSON doesn't match the XML source?

The JSON standard does not guarantee attribute order; the tool maps attributes in source-code order. If your business is order-sensitive, rebuild the JSON as an ordered array using lodash's toPairs or similar tools. Note that most JavaScript engines (V8, SpiderMonkey) do preserve string key insertion order.

A single element with the same tag name doesn't become an array - how to handle?

The tool only converts to an array when it detects multiple sibling elements with the same tag name; if there is only one such element, the tool keeps it as a single object. To force array-ification (even with just one element), wrap with lodash's castArray after conversion: [result].flat() or enforce arrays via JSON Schema validation.

How do I preserve special characters in XML attributes (like <, &)?

DOMParser auto-unescapes attribute values; the tool keeps the unescaped content. If the original XML has &lt;, the converted JSON value is <. This is standard XML behavior and matches user expectations. If you need to keep the original escaped form, use a custom XML tokenizer to replace DOMParser.

Why does YAML output have no type information?

YAML supports types natively (12 is number, true is boolean, null is null), but the tool's simple YAML converter serializes all values as strings. To preserve types, use a mature YAML library like js-yaml, or enforce types via JSON Schema validation on the parser side.

How are XML Processing Instructions (PI) handled?

DOMParser preserves XML processing instructions (e.g. <?xml-stylesheet ...?>) as ProcessingInstruction nodes in document.firstChild. The tool currently only traverses Element nodes, so processing instructions are ignored. To preserve them, manually extract document.firstChild.nodeValue before use.

What can I open the downloaded .json file with?

The downloaded output.json is a UTF-8 encoded standard JSON file. You can open it with any text editor (VS Code, Sublime, Notepad++) or specialized JSON tool (jq, JSDoc), or drag it into a browser to view the formatted structure. Almost all programming languages (JavaScript, Python, Node.js, Java, Go, etc.) have built-in JSON parsers.

Glossary

XML (eXtensible Markup Language)
Extensible markup language defined by W3C in 1998. Uses angle-bracket tags to describe data structure and content, and supports namespaces, schema validation, and XSLT transformation. It is the standard format for SOAP Web Services, Office Open XML, RSS, and Atom.
JSON (JavaScript Object Notation)
Lightweight data-interchange format based on JavaScript object syntax but independent of any programming language. Supports six basic types: object ({}), array ([]), string, number, boolean, and null. It is the de-facto standard for modern Web APIs, NoSQL databases, and the JavaScript ecosystem.
DOMParser
Browser-native API (W3C DOM standard) that parses XML or HTML strings into a DOM tree. All modern browsers (Chrome, Firefox, Safari, Edge) have it built-in, so no third-party library is needed. With the DOM tree you can easily traverse, query, and modify XML content.
xml-formatter
Lightweight JavaScript library (under 30KB) for formatting (prettyPrint) and compressing (minify) XML documents. Supports custom indentation, line separators, and collapseContent options. The tool uses it to provide XML format and compression.
Attribute mapping
How XML element attributes map to JSON object fields. The tool uses a direct-mapping approach: <book id="1"> becomes {id: "1"}, without any @ prefix. This produces cleaner JSON and simpler TypeScript interface definitions.
Repeated-element array-ification
Sibling XML elements with the same tag name (such as multiple <item>) are auto-merged into a JSON array. This is a key design decision in XML-to-JSON conversion that aligns with JSON's list semantics and avoids data loss.
value field
The tool's convention for XML element text content. The element <title>Great Gatsby</title> becomes {value: "Great Gatsby"}. If the element has both attributes and text, the attributes and value are stored as siblings in the same object.
YAML (YAML Ain't Markup Language)
Human-friendly data serialization format, widely used in Kubernetes, Docker Compose, Ansible, and GitHub Actions configuration files. The tool supports simple YAML output with 2-space indent, list prefix -, and key:value syntax.
SOAP (Simple Object Access Protocol)
XML-based Web service communication protocol. SOAP messages are wrapped in a SOAP envelope (XML namespace) and contain a header and body (XML payload). The tool parses SOAP messages into JSON for use by modern JavaScript services.
RSS / Atom feed
XML-based content syndication formats. RSS 2.0 organizes content in a <rss><channel><item> structure, while Atom uses <feed><entry>. The tool converts RSS/Atom to JSON arrays for display on the frontend or aggregation into a database.
XML namespace
A mechanism to avoid element name conflicts using the xmlns attribute, in the form xmlns:prefix="uri". DOMParser natively supports namespaces; namespace prefixes are preserved as part of the element name in the JSON.
CDATA section
Special XML syntax <![CDATA[...]]> for embedding text with special characters (such as <, >, &) without escaping. DOMParser merges CDATA content into the element's textContent, and the tool treats it as regular text.
tryFixXML
The tool's built-in XML repair function that auto-adds missing XML declarations (<?xml version="1.0" encoding="UTF-8"?>) and completes the trailing slash for self-closing tags like br, hr, and img. It handles dirty data from legacy systems or non-standard third-party APIs.
prettyPrint
Output mode of the xml-formatter library. When enabled, the generated XML automatically includes indentation and line breaks (such as 2-space indentation), making it highly readable; when disabled, the output is compact without whitespace (minified).

XML element to JSON field mapping rules

The tool's conversion rules based on DOMParser:

XML structureXML exampleJSON outputMapping rule
element with attrs<book id="1" category="fiction"/>{"id": "1", "category": "fiction"}Attributes map directly to object fields (no @ prefix)
element with text<title>Great Gatsby</title>{"value": "Great Gatsby"}Element text content goes into the value field
attrs + text<price currency="USD">12.99</price>{"currency": "USD", "value": "12.99"}Attributes and text are siblings in the same object
no attrs, no text<book id="1"/>{"id": "1"}Only attributes, no value field
nested elements<book><title>Gatsby</title></book>{"title": {"value": "Gatsby"}}Child elements become object fields
repeated elements<books><book/><book/></books>{"book": [{}, {}]}Repeated sibling elements are auto-merged into an array
root element<bookstore>...</bookstore>{"bookstore": {...}}Root node is wrapped in { [tagName]: ... }
namespace prefix<svg:circle/>{"svg:circle": {...}}DOMParser natively supports namespaces

JSON vs YAML output comparison

The two output formats supported by the tool, with their features and use cases:

DimensionJSONYAMLNotes
Syntax{ } : [ ] conciseindents + - listsJSON more concise, YAML more readable
Data typesnative number/bool/nullnative number/bool/nullBoth preserve types
Indentation2-space indent2-space indentThe tool uniformly uses 2 spaces
Arrays[1, 2, 3]- 1\n- 2\n- 3JSON uses brackets, YAML uses dashes
Commentsnot supported (standard)# commentsYAML supports comments
Readabilitymedium (bracket noise)high (close to natural language)YAML is more readable
Use casesREST API, frontend-backendK8s, Docker, CI/CDWeb uses JSON, config uses YAML

XML vs JSON format comparison

A comparison of the two data formats across different dimensions, to help understand when to choose XML or JSON:

DimensionXMLJSONNotes
Syntax< > </> verbose{ } : [ ] conciseJSON syntax is more concise; XML tags are more verbose but readable
Data typesAll stringsNative number/bool/nullJSON preserves types; XML needs schema validation
ArraysRepeated elements <i>1</i><i>2</i>Native [1,2,3]JSON arrays are concise; XML arrays rely on naming conventions
Comments<!-- comment -->Not supported (standard)XML supports comments; JSON standard does not
Namespacesxmlns supportedNoneXML avoids name conflicts in large documents
Schema validationXSD / DTDJSON SchemaBoth have mature schema validation mechanisms
Parse performanceSlower (tag overhead)Faster (~3-5x)JSON parsing is simpler; XML parsing is more complex
Use casesSOAP, enterprise, OfficeREST API, frontend-backendModern web uses JSON; traditional enterprise uses XML

Privacy & Security

This XML to JSON tool runs entirely in your browser. XML parsing (powered by the browser's native DOMParser), DOM tree traversal, JSON serialization, and YAML conversion all happen in client-side JavaScript; xml-formatter is the only external dependency (a sub-30KB npm package). Original XML data is never sent to a server. File uploads use the browser's native FileReader API and never go through an intermediate service. The tool uses no tracking cookies and collects no input or usage data. All input and output are cleared from memory as soon as the page is closed or refreshed. Safe to use for XML messages that contain sensitive business data (order information, user credentials, enterprise API responses).

Authoritative References