becomes \"script\": \"var x = 1 < 2;\" in JSON. The less-than sign that required CDATA wrapping in XML is simply part of the string in JSON, since JSON strings use backslash escaping and do not have the XML restriction on bare < characters. No special handling is needed in your code — the CDATA content is available as a normal string value."}},{"@type":"Question","name":"How are XML namespaces handled?","acceptedAnswer":{"@type":"Answer","text":"Namespace declarations like xmlns:xsi=\"http://...\" are preserved as attributes with the @_ prefix: \"@_xmlns:xsi\": \"http://...\". Namespace-prefixed element names like xsi:type and soap:Envelope are preserved as-is in the JSON key name. Namespace resolution — looking up the prefix in xmlns declarations and replacing it with the full URI — is not performed by fast-xml-parser in its default configuration. SOAP envelopes, WSDL files, and XML Schema documents all make heavy use of namespaces, so their JSON output will contain many @_xmlns and namespace-prefixed keys. If your downstream system does not need namespace information, strip the @_xmlns keys from the JSON output after conversion using jq: del(.. | objects | with_entries(select(.key | startswith(\"@_xmlns\"))))."}},{"@type":"Question","name":"What does an element with both attributes and text content look like in JSON?","acceptedAnswer":{"@type":"Answer","text":"An element that has both attributes and text content — such as 9.99 — produces {\"@_currency\": \"USD\", \"#text\": \"9.99\"}. The text content is stored under the special key #text to avoid collision with the attribute keys that share the same parent object. This pattern is very common in XML used for data interchange, where attributes carry metadata and text content carries the actual value. When consuming this output in code, check for the #text key when you need the value: const value = typeof node === 'string' ? node : node['#text']. An element with only text content and no attributes returns a plain string without a #text wrapper, so you need to handle both shapes."}},{"@type":"Question","name":"How are empty XML elements represented in JSON?","acceptedAnswer":{"@type":"Answer","text":"A self-closing element like
or an empty element

with no attributes and no content becomes an empty string \"\" in the JSON output. An element with only attributes and no text content, like \"logo\"/, becomes an object with only @_ keys: {\"@_src\": \"x.png\", \"@_alt\": \"logo\"}. This distinction is important when writing code to consume the JSON: an empty element returns an empty string rather than null or an empty object, so checking if (node) will evaluate to false for an empty element, while if (node !== '') correctly distinguishes between an empty element and an absent one."}},{"@type":"Question","name":"Can I convert XML to JSON in Python?","acceptedAnswer":{"@type":"Answer","text":"Yes, using xmltodict: import xmltodict, json; data = xmltodict.parse(xml_string); json_str = json.dumps(data, indent=2). xmltodict uses the @ prefix for attributes (not @_), and stores text content under #text — the same convention as fast-xml-parser. Install via pip install xmltodict. The standard library's xml.etree.ElementTree can also parse XML and you can build a JSON structure manually, but xmltodict is simpler for most use cases. For large XML files, xmltodict supports streaming via xmltodict.parse(fobj, item_depth=2, item_callback=callback), which calls a callback for each top-level item without loading the entire document into memory — important for files over a few megabytes."}},{"@type":"Question","name":"Can I convert XML to JSON in Node.js?","acceptedAnswer":{"@type":"Answer","text":"Yes, using fast-xml-parser: import { XMLParser } from 'fast-xml-parser'; const parser = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: '@_' }); const data = parser.parse(xmlString); const json = JSON.stringify(data, null, 2). fast-xml-parser is the same library used to power this browser tool, so programmatic output will match what you see here. Install via npm install fast-xml-parser. The ignoreAttributes: false option is required to include attributes in the output — by default, fast-xml-parser strips them. The attributeNamePrefix: '@_' option sets the prefix used for attribute keys. fast-xml-parser v5 is TypeScript-native and supports Node.js, Deno, and browsers. It is significantly faster than xml2js for large documents and is the recommended library for new projects."}},{"@type":"Question","name":"Is my data sent to a server?","acceptedAnswer":{"@type":"Answer","text":"No. The conversion runs entirely in your browser using fast-xml-parser v5. Your data never leaves your machine and no account or sign-up is required. The fast-xml-parser library is bundled as a static JavaScript asset and loaded from the same origin as the page. No external API calls or telemetry requests are made when you convert XML. This makes the tool safe to use with sensitive XML documents such as SOAP API responses containing credentials, enterprise configuration files, or medical or financial data in HL7 or FIXML formats. The tool also runs fully offline after the initial page load because all scripts are cached by the browser. Session state is kept in localStorage only, and is never transmitted to any server."}},{"@type":"Question","name":"Why does the same XML element sometimes produce a string and sometimes an object?","acceptedAnswer":{"@type":"Answer","text":"fast-xml-parser returns a plain string when an element has only text content and no attributes or child elements, and returns an object when it has attributes or children. Alice produces the string \"Alice\", but Alice produces the object {\"@_lang\": \"en\", \"#text\": \"Alice\"}. This means the same tag name can produce different JSON shapes depending on whether it carries attributes in a particular document. Write defensive consumers: const name = typeof node === 'string' ? node : node['#text']. This behaviour is consistent across fast-xml-parser, xmltodict, and xml2js — it is a fundamental characteristic of XML-to-JSON conversion rather than a library-specific choice. If your XML schema guarantees all elements of a certain type always have attributes, the shape will be consistent and you can rely on the object form."}}]}]}
DevFormatter

XML → JSON

 

XML to JSON Converter

XML to JSON conversion parses an XML document and maps its constructs to JSON equivalents: element names become object keys, text content becomes string values, repeated sibling elements become arrays, and attributes are prefixed with @_ to distinguish them from child element keys. This tool uses fast-xml-parser v5, the same convention used by xmltodict (Python) and xml2js (Node.js). All conversion runs in the browser with no data sent to any server.

How XML to JSON Conversion Works

Last updated: November 2026

XML (Extensible Markup Language) is a tag-based format used for documents, web services, configuration, and data interchange. This converter parses your XML using fast-xml-parser v5, which produces a JavaScript object representing the document tree. Attributes are preserved with the @_ prefix, repeated sibling elements become arrays, and the result is serialized to formatted JSON.

Paste your XML into the left panel and click Convert to JSON — or just paste and the conversion runs automatically. The JSON output appears in the right panel and can be copied or downloaded.

XML → JSON Mapping Reference

XML's richer data model requires conventions to represent in JSON's simpler type system.

XML construct JSON output Example
<name>text</name> "name": "text" Text-only element → string value
id="1" (attribute) "@_id": "1" Attributes get @_ prefix
Nested elements Nested object "parent": {"child": "val"}
Repeated siblings Array "item": ["a", "b", "c"]
Attrs + text content "#text" key "@_id": "1", "#text": "val"
<!-- comment --> (lost) JSON has no comment syntax
<![CDATA[...]]> "plain string" CDATA markers stripped
<br/> (empty) "" Self-closing → empty string

The @_ Attribute Convention

XML elements can have both child elements and attributes with the same name. For example, <item id="1"><id>2</id></item> has both an id attribute and an id child element. To avoid key collisions, fast-xml-parser prefixes attribute names with @_.

This produces {"@_id": "1", "id": "2"} — both values are accessible without ambiguity. The same @_ convention is used by xmltodict (Python) and xml2js (Node.js), making it the industry standard for XML-to-JSON libraries.

Tips & Tricks

Single vs. multiple elements

When the XML source has exactly one <item>, the JSON field is a plain object. When it has two or more, it becomes an array. Write defensive consumers: const items = Array.isArray(data.root.item) ? data.root.item : [data.root.item].

Attributes land under @_

<book id="1"> becomes {"@_id": "1"}. When looking up attribute values programmatically, always use the @_ prefix: book['@_id'].

The #text key

An element with both attributes and text content (like <name lang="en">Alice</name>) stores the text under #text. Check for this key when mixing attributes and content in the same element.

XML namespaces are not resolved

Namespace prefixes like xsi:type remain as-is in the JSON key. Strip or remap them after conversion if your downstream system doesn't expect the prefix.

SOAP and WSDL responses

SOAP envelopes are XML. Converting SOAP API responses is a common use case — the output will have @_xmlns and @_xmlns:xsi attributes preserved from the envelope wrapper.

Large XML files

The converter holds the full parsed tree in memory. Files above ~5 MB may be slow in the browser. For large XML, use streaming parsers like sax (Node.js) or xml.etree.ElementTree (Python) with incremental processing.

Code Examples

Node.js

import { XMLParser } from 'fast-xml-parser';
import fs from 'fs';

const xml = fs.readFileSync('data.xml', 'utf8');
const parser = new XMLParser({
  ignoreAttributes: false,
  attributeNamePrefix: '@_',
});
const data = parser.parse(xml);
const json = JSON.stringify(data, null, 2);
fs.writeFileSync('data.json', json);

Python

import xmltodict
import json

with open('data.xml') as f:
    data = xmltodict.parse(f.read())

json_str = json.dumps(data, indent=2)
with open('data.json', 'w') as f:
    f.write(json_str)

# Install: pip install xmltodict
# xmltodict uses the same @_ convention for attributes

CLI

# Using xq (XML-aware jq wrapper — pip install xq)
xq . data.xml > data.json

# Using Python xmltodict one-liner
python3 -c "import xmltodict,json,sys; print(json.dumps(xmltodict.parse(sys.stdin.read()), indent=2))" < data.xml

# Using Node.js + fast-xml-parser
node -e "const {XMLParser}=require('fast-xml-parser'),fs=require('fs'); const p=new XMLParser({ignoreAttributes:false,attributeNamePrefix:'@_'}); console.log(JSON.stringify(p.parse(fs.readFileSync(process.argv[1],'utf8')),null,2))" data.xml

Frequently Asked Questions

How does XML to JSON conversion work?
XML to JSON conversion parses the XML document into an in-memory tree, then maps each construct to its closest JSON equivalent. Element names become object keys, text content becomes string values, child elements become nested objects, and repeated sibling elements become arrays. XML attributes are preserved as keys prefixed with @_ to distinguish them from child element keys. This tool uses fast-xml-parser v5, a high-performance JavaScript XML parser that handles all well-formed XML including namespaces, CDATA sections, processing instructions, and DOCTYPE declarations. The parsed JavaScript object is then serialized to JSON using JSON.stringify(). The process is lossy in some respects: XML comments are discarded, attribute order is not preserved, and the @_ prefix convention is an approximation since JSON has no native concept of attribute-versus-child-element distinction.
How are XML attributes represented in JSON?
Attributes are prefixed with @_ and stored as siblings of child elements within the same object. For example, <book id="1"><title>XML Guide</title></book> becomes {"@_id": "1", "title": "XML Guide"}. This convention avoids name collisions between attribute names and child element names when both use the same identifier. The @_ prefix is the industry-standard convention used by fast-xml-parser (JavaScript), xmltodict (Python), and xml2js (Node.js), making JSON produced by any of these libraries structurally compatible. When accessing attribute values programmatically, always use the @_ prefix: data.book['@_id']. All attribute values are returned as strings, even numeric-looking attributes like id="1" — cast to numbers as needed in your code.
How are repeated XML elements handled?
Repeated sibling elements with the same tag name are automatically converted to a JSON array. For example, <list><item>a</item><item>b</item></list> becomes {"list": {"item": ["a", "b"]}}. However, a single <item> element remains a plain string or object, not a single-element array. This inconsistency — where the same field name can be a string or an array depending on the number of sibling elements — is the most common issue when writing code to consume XML-to-JSON output. The idiomatic fix is defensive normalization: const items = Array.isArray(data.root.item) ? data.root.item : [data.root.item]. Some XML-to-JSON libraries offer an isArray configuration option to force specific element names to always be arrays, which eliminates this problem.
What happens to XML comments?
XML comments (<!-- text -->) are discarded during parsing. JSON has no comment syntax and fast-xml-parser ignores comments by default. If you need to preserve comment content, the best approach is to convert comments to dedicated child elements or attributes before conversion — for example, replace <!-- This is the user ID --><id>42</id> with <id comment="This is the user ID">42</id>. Alternatively, fast-xml-parser can be configured to treat HTML entities and certain patterns as named nodes if the comment content follows a consistent structure. For documentation purposes, it is usually better to treat XML-to-JSON as a data-only conversion and maintain separate documentation outside the data format.
How is CDATA handled?
CDATA sections (<![CDATA[...]]>) are treated as text content and appear as plain string values in the JSON output. The CDATA markers themselves are stripped, leaving only the raw text content. CDATA is typically used in XML to embed content that contains characters that would otherwise need escaping, such as HTML markup, JavaScript code, or SQL queries. For example, <script><![CDATA[var x = 1 < 2;]]></script> becomes "script": "var x = 1 < 2;" in JSON. The less-than sign that required CDATA wrapping in XML is simply part of the string in JSON, since JSON strings use backslash escaping and do not have the XML restriction on bare < characters. No special handling is needed in your code — the CDATA content is available as a normal string value.
How are XML namespaces handled?
Namespace declarations like xmlns:xsi="http://..." are preserved as attributes with the @_ prefix: "@_xmlns:xsi": "http://...". Namespace-prefixed element names like xsi:type and soap:Envelope are preserved as-is in the JSON key name. Namespace resolution — looking up the prefix in xmlns declarations and replacing it with the full URI — is not performed by fast-xml-parser in its default configuration. SOAP envelopes, WSDL files, and XML Schema documents all make heavy use of namespaces, so their JSON output will contain many @_xmlns and namespace-prefixed keys. If your downstream system does not need namespace information, strip the @_xmlns keys from the JSON output after conversion using jq: del(.. | objects | with_entries(select(.key | startswith("@_xmlns")))).
What does an element with both attributes and text content look like in JSON?
An element that has both attributes and text content — such as <price currency="USD">9.99</price> — produces {"@_currency": "USD", "#text": "9.99"}. The text content is stored under the special key #text to avoid collision with the attribute keys that share the same parent object. This pattern is very common in XML used for data interchange, where attributes carry metadata and text content carries the actual value. When consuming this output in code, check for the #text key when you need the value: const value = typeof node === 'string' ? node : node['#text']. An element with only text content and no attributes returns a plain string without a #text wrapper, so you need to handle both shapes.
How are empty XML elements represented in JSON?
A self-closing element like <br/> or an empty element <br></br> with no attributes and no content becomes an empty string "" in the JSON output. An element with only attributes and no text content, like <img src="x.png" alt="logo"/>, becomes an object with only @_ keys: {"@_src": "x.png", "@_alt": "logo"}. This distinction is important when writing code to consume the JSON: an empty element returns an empty string rather than null or an empty object, so checking if (node) will evaluate to false for an empty element, while if (node !== '') correctly distinguishes between an empty element and an absent one.
Can I convert XML to JSON in Python?
Yes, using xmltodict: import xmltodict, json; data = xmltodict.parse(xml_string); json_str = json.dumps(data, indent=2). xmltodict uses the @ prefix for attributes (not @_), and stores text content under #text — the same convention as fast-xml-parser. Install via pip install xmltodict. The standard library's xml.etree.ElementTree can also parse XML and you can build a JSON structure manually, but xmltodict is simpler for most use cases. For large XML files, xmltodict supports streaming via xmltodict.parse(fobj, item_depth=2, item_callback=callback), which calls a callback for each top-level item without loading the entire document into memory — important for files over a few megabytes.
Can I convert XML to JSON in Node.js?
Yes, using fast-xml-parser: import { XMLParser } from 'fast-xml-parser'; const parser = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: '@_' }); const data = parser.parse(xmlString); const json = JSON.stringify(data, null, 2). fast-xml-parser is the same library used to power this browser tool, so programmatic output will match what you see here. Install via npm install fast-xml-parser. The ignoreAttributes: false option is required to include attributes in the output — by default, fast-xml-parser strips them. The attributeNamePrefix: '@_' option sets the prefix used for attribute keys. fast-xml-parser v5 is TypeScript-native and supports Node.js, Deno, and browsers. It is significantly faster than xml2js for large documents and is the recommended library for new projects.
Is my data sent to a server?
No. The conversion runs entirely in your browser using fast-xml-parser v5. Your data never leaves your machine and no account or sign-up is required. The fast-xml-parser library is bundled as a static JavaScript asset and loaded from the same origin as the page. No external API calls or telemetry requests are made when you convert XML. This makes the tool safe to use with sensitive XML documents such as SOAP API responses containing credentials, enterprise configuration files, or medical or financial data in HL7 or FIXML formats. The tool also runs fully offline after the initial page load because all scripts are cached by the browser. Session state is kept in localStorage only, and is never transmitted to any server.
Why does the same XML element sometimes produce a string and sometimes an object?
fast-xml-parser returns a plain string when an element has only text content and no attributes or child elements, and returns an object when it has attributes or children. <name>Alice</name> produces the string "Alice", but <name lang="en">Alice</name> produces the object {"@_lang": "en", "#text": "Alice"}. This means the same tag name can produce different JSON shapes depending on whether it carries attributes in a particular document. Write defensive consumers: const name = typeof node === 'string' ? node : node['#text']. This behaviour is consistent across fast-xml-parser, xmltodict, and xml2js — it is a fundamental characteristic of XML-to-JSON conversion rather than a library-specific choice. If your XML schema guarantees all elements of a certain type always have attributes, the shape will be consistent and you can rely on the object form.

Related Tools

Other free developer tools available on DevFormatter.