XML to JSON Converter
This XML to JSON converter transforms XML documents into JSON and back. Handles attributes, nested elements, and sibling arrays.
This tool converts XML documents to JSON and JSON back to XML using the browser's native DOMParser. It handles attributes (prefixed with @), nested elements, text content, and repeated siblings that become JSON arrays. Paste XML on the left and get structured JSON on the right, or reverse the process. Nothing is sent to a server - parsing happens entirely on your machine.
About XML to JSON Converter
How XML Maps to JSON
XML and JSON use different data models, so conversion follows a small set of conventions. XML has elements, attributes, text content, and mixed content. JSON has objects, arrays, strings, and numbers. The mapping below is the one used by this tool and matches popular libraries like fast-xml-parser and xml2js.
| XML Feature | JSON Convention | Example XML | Example JSON |
|---|---|---|---|
| Element | Object key | <name>Alice</name> | {"name": "Alice"} |
| Attribute | Key prefixed with @ | <book id="5"> | {"book": {"@id": "5"}} |
| Text content (mixed) | #text key | <p>Hello <b>world</b></p> | {"p": {"#text": "Hello ", "b": "world"}} |
| Repeated siblings | Array | <item>A</item><item>B</item> | {"item": ["A", "B"]} |
| Nested elements | Nested objects | <a><b><c>1</c></b></a> | {"a": {"b": {"c": "1"}}} |
| Empty element | Empty string or null | <br/> | {"br": ""} |
The @ prefix for attributes is the most widely used convention. Some converters use a "$" prefix or nest attributes under a separate "$attrs" object - always check what your downstream system expects before exchanging data.
Worked Example: Converting a Bookstore
Here is the round-trip conversion the tool performs on the built-in sample. The input XML has two book elements under a single bookstore root, each with a category attribute and a nested title element with its own lang attribute.
XML input:
<bookstore>
<book category="fiction">
<title lang="en">The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<year>1925</year>
</book>
<book category="non-fiction">
<title lang="en">A Brief History of Time</title>
<author>Stephen Hawking</author>
<year>1988</year>
</book>
</bookstore>
JSON output:
{
"bookstore": {
"book": [
{ "@category": "fiction", "title": { "@lang": "en", "#text": "The Great Gatsby" }, "author": "F. Scott Fitzgerald", "year": "1925" },
{ "@category": "non-fiction", "title": { "@lang": "en", "#text": "A Brief History of Time" }, "author": "Stephen Hawking", "year": "1988" }
]
}
}
Note how the two book siblings become an array, attributes gain the @ prefix, and the title element becomes an object because it has both an attribute and text content. If there had been only one book, it would be an object rather than an array - this is the consistency trap covered in the next section.
The Repeated Sibling Problem
This is the trickiest part of XML-to-JSON conversion. In XML, sibling elements can share the same tag name. In JSON, object keys must be unique, so same-named siblings have to be grouped into an array. The side effect is that a single child is a scalar or object, while multiple children suddenly become an array.
| XML | JSON (with array grouping) | Note |
|---|---|---|
| <items><item>A</item></items> | {"items": {"item": "A"}} | Single child - string value |
| <items><item>A</item><item>B</item></items> | {"items": {"item": ["A", "B"]}} | Multiple children - becomes array |
Downstream code needs to handle both shapes. The defensive pattern in JavaScript is const arr = Array.isArray(value) ? value : [value] before iterating. Libraries like fast-xml-parser expose an alwaysCreateTextNode or isArray callback so specific element names are always emitted as arrays - useful when a schema guarantees a collection regardless of count.
XML vs JSON - When to Use Each
JSON dominates new APIs and web traffic, but XML remains the right tool for document-oriented data, strict schemas, and regulated industries. The table below summarises the practical differences.
| Aspect | XML | JSON |
|---|---|---|
| Data model | Document-oriented (elements, attributes, mixed content) | Data-oriented (objects, arrays, scalars) |
| Schema validation | XSD, DTD, RelaxNG - mature, widely tooled | JSON Schema - growing but less established |
| Namespaces | Full namespace support (xmlns) | No built-in concept |
| Comments | Yes (<!-- -->) | No (stripped by JSON.parse) |
| Query languages | XPath, XQuery, XSLT | JSONPath, jq |
| Parsing modes | SAX (streaming), DOM (tree) | JSON.parse (entire document) |
| Verbosity | Higher (closing tags, attributes) | Lower (concise syntax) |
| Mixed content | First-class (text between elements) | Awkward (needs #text key convention) |
Where XML Is Still the Default
| Domain | Format | Why XML |
|---|---|---|
| Enterprise APIs | SOAP / WSDL | Legacy systems, strict contracts, WS-Security |
| RSS / Atom feeds | RSS 2.0, Atom | Established standard since the early 2000s |
| Sitemaps | sitemap.xml | sitemaps.org protocol used by Google and Bing |
| Office documents | OOXML (.docx, .xlsx, .pptx) | Complex document structure with styles |
| Android | AndroidManifest.xml, resource layouts | Platform convention |
| SVG | Scalable Vector Graphics | Markup-based image format, part of HTML5 |
| Banking / payments | ISO 20022 | Regulated standard with strict schema |
| Healthcare | HL7 v2, HL7 FHIR (supports XML and JSON) | Interoperability standard |
Most new public APIs ship JSON by default - Stripe, GitHub, OpenAI, Slack, Shopify, and the major cloud providers all use JSON. XML remains dominant in industries where schema enforcement and compliance are non-negotiable.
How the Browser Parser Works
This tool uses the native DOMParser.parseFromString(xml, 'application/xml') API, which has been available in every major browser since July 2015 per MDN. Unlike throwing on malformed input, DOMParser returns a document containing a <parsererror> element - the converter detects this element and surfaces the message so you can fix the XML. The XML 1.0 specification the parser implements is the W3C Fifth Edition (2008, still current as of 2026), plus Namespaces in XML 1.0 Third Edition.
Because parsing happens client-side, there is no upload size limit beyond what your browser will hold in memory. Tabs typically handle tens of megabytes of XML without issue, but multi-gigabyte documents should be processed server-side with a streaming parser like SAX or StAX.
Common Conversion Gotchas
- Numeric strings stay strings. XML has no type system - every text node is a string. JSON.parse will not turn "1925" into a number for you. If your downstream code needs numeric types, post-process after conversion or use a schema-aware library.
- Whitespace is lost between elements. The converter collapses whitespace-only text nodes. Preserving them requires a different mode (fast-xml-parser's
preserveOrder: true) which this tool does not implement. - Namespaces are flattened. A prefix like
<atom:entry>becomes the key "atom:entry" - the namespace URI is dropped. If namespace-aware round-tripping matters, use a dedicated library. - CDATA sections become plain text.
<![CDATA[raw & text]]>converts to "raw & text" with no marker indicating it was originally CDATA. - Comments and processing instructions are dropped. Only elements, attributes, and text survive the round trip.
- Mixed content order is not preserved. JSON objects have no guaranteed key order, so
<p>Hello <b>world</b> today</p>cannot reconstruct to identical XML. Text-heavy documents should stay in XML.
Library Comparison for Server-Side Work
If you need to automate XML-to-JSON conversion outside the browser, these are the most widely used libraries by ecosystem. All four actively maintain releases and handle millions of downloads per week across npm and PyPI.
| Library | Language | Style | Notable Features |
|---|---|---|---|
| fast-xml-parser | Node.js / browser | DOM-style | Very fast, configurable attribute prefix, preserveOrder mode, isArray callback |
| xml2js | Node.js | DOM-style | SAX under the hood, callback and Promise APIs, lots of options for attribute and charkey handling |
| lxml | Python | DOM + XPath | C-based, very fast, full XPath and XSLT support, namespace-aware |
| xmltodict | Python | DOM-style | Drop-in XML to dict converter matching the @ attribute convention this tool uses |
For huge documents (hundreds of megabytes or more), pick a SAX-style parser - libxml2 in C, Apache Xerces in Java, or lxml's iterparse in Python. DOM parsers including this tool's DOMParser must hold the entire document in memory.
Security Considerations When Parsing XML
XML has a few parsing quirks that have caused real security incidents. Browser DOMParser is safe against most of them because the XML profile disables external entities by default, but the same cannot be said for every server-side parser.
- XXE (XML External Entity) attacks exploit parsers that resolve external DTD entities, potentially exposing local files or triggering server-side requests. OWASP lists XXE among its long-running Top 10 risks. Disable external entity resolution on server parsers (Python's defusedxml, Java's XMLConstants.FEATURE_SECURE_PROCESSING).
- Billion laughs / entity expansion attacks use nested entity definitions to expand a tiny document into gigabytes of memory. Set an entity expansion limit or use a parser that caps expansion by default.
- DTD fetching can trigger network calls when a schema is referenced. Disable DTD loading in production.
- Encoding confusion. Always respect the XML declaration's encoding attribute; mis-decoding can bypass security filters that scan the text.
Because this tool runs in the browser and uses application/xml mode, DTDs and external entities are not resolved - the main risk is simply pasting data you did not intend to share, which is why conversion stays on your device.
Converting JSON Back to XML
The reverse conversion follows the same conventions. Object keys become element names, keys prefixed with "@" become attributes, arrays become repeated sibling elements, and "#text" becomes text content. Special characters are escaped (&, <, >, ") so the output is always valid XML. The output is indented two spaces per level for readability.
| JSON Input | XML Output |
|---|---|
| {"user": {"@id": "1", "name": "Alice"}} | <user id="1"><name>Alice</name></user> |
| {"items": {"item": ["A", "B"]}} | <items><item>A</item><item>B</item></items> |
| {"p": {"#text": "Hello ", "b": "world"}} | <p>Hello <b>world</b></p> |
JSON-to-XML is lossier than the forward direction because JSON has no concept of namespaces, processing instructions, or DTDs. If you need a strict round-trip, keep the XML source alongside the JSON rather than regenerating from JSON.
For adjacent formats, the YAML to JSON Converter handles YAML input, the JSON Formatter adds indentation and syntax highlighting to the output, and the JSON to CSV Converter flattens nested structures into rows and columns for spreadsheets. All three run entirely in the browser.
Sources
Frequently Asked Questions
How does the converter handle XML attributes?
XML attributes are converted to JSON properties prefixed with the "@" symbol. For example, <book id="123"> becomes {"book":{"@id":"123"}}. This convention keeps attributes visually distinct from child elements in the JSON output, and it is a widely used pattern in XML-to-JSON conversion.
What happens with repeated child elements of the same name?
When an XML element has multiple children with the same tag name, they are automatically grouped into a JSON array. For example, <items><item>A</item><item>B</item></items> becomes {"items":{"item":["A","B"]}}. This ensures the structure is preserved accurately.
Can I convert JSON back to XML?
Yes. The tool supports bidirectional conversion. Paste JSON in the right pane and click "JSON to XML" to generate XML output. The converter follows the same conventions in reverse - properties starting with "@" become attributes, arrays become repeated sibling elements, and the "#text" key becomes text content.
What XML parser does this tool use?
The tool uses the browser's native DOMParser API, which is the same parser browsers use to process web pages. This means it handles well-formed XML reliably without any external libraries. If your XML has syntax errors, the parser will report them clearly so you can fix the issue.
Is my data processed on a server?
No. Everything runs in your browser using JavaScript and the native DOMParser. Your XML and JSON data never leaves your machine, so you can safely convert files that contain sensitive configuration, API responses, or proprietary data.
Related Tools
Link to this tool
Copy this HTML to link to this tool from your website or blog.
<a href="https://toolboxkit.io/tools/xml-to-json-converter/" title="XML to JSON Converter - Free Online Tool">Try XML to JSON Converter on ToolboxKit.io</a>