What is XML to JSON? Converting Markup to Data Explained
A XML to JSON converter transforms Extensible Markup Language (XML) β the tag-based, document-centric format for RSS, sitemaps, SVG, SOAP, Office files, and Java configs β into JSON (JavaScript Object Notation) β the lightweight, object-and-array format that JavaScript, REST APIs, MongoDB, Firebase, and modern frontends speak natively. While XML represents data as nested tags with attributes like <book id="bk101"><title>XML Guide</title></book>, JSON represents the same information as {"book":{"@attributes":{"id":"bk101"},"title":"XML Guide"}} or as an array when siblings repeat. Our XML to JSON converter bridges these worlds in your browser using the browser's native DOMParser to parse XML and a recursive mapper that walks the DOM tree, turning every element into a JSON object or string while preserving hierarchy, attributes, text nodes, and repeated elements.
The conversion is non-trivial because XML and JSON have different data models. XML allows attributes on elements (id="bk101"), mixed content where text and elements interleave, multiple sibling elements with the same name (<book><book>), CDATA sections (<![CDATA[ <html> ]]>), comments, processing instructions, and namespaces like xmlns:svg. JSON has only objects, arrays, strings, numbers, booleans and null β no attributes or mixed content. Different xml to json libraries make different trade-offs: some prefix attribute keys with @ or -, some put text under #text or _text, and some collapse single-child arrays versus always using arrays. Our tool follows the widely adopted convention popularized by xml2js and browser utilities: attributes go under "@attributes", text-only elements become plain strings, repeated sibling tags automatically become arrays, CDATA goes under "#cdata", and mixed text is stored as "#text". This yields predictable, spec-friendly JSON that works with JSON.parse, fetch(), and JSON databases without manual post-processing. And because everything runs via client-side JavaScript with DOMParser + recursion, your XML never leaves your device β essential for private SOAP payloads, internal sitemaps, and configs containing tokens or PII.
Why Convert XML to JSON? Benefits for Developers, APIs & Data Teams
XML remains entrenched in enterprise and SEO infrastructure β sitemaps, RSS/Atom feeds, SAML, SOAP WSDLs, SVG assets, and Spring/Maven configs are all XML. Yet new code is almost entirely JSON. Converting unlocks interoperability without rewriting upstream systems.
| Benefit | How XML to JSON Helps | Who Benefits Most |
|---|---|---|
| π API Modernization | Turn SOAP XML responses into JSON that React, Node.js, and fetch can JSON.parse immediately β no XML parser in app code | Frontend & backend developers |
| π Data Analysis | Load sitemap or RSS XML into Python pandas, Jupyter, or BI tools after converting to JSON/CSV pipeline | Data engineers, analysts |
| β‘ JavaScript Native | JSON is directly assignable as const data = {...} and supports map/filter/reduce without DOM traversal | JS/TS, React, Next.js developers |
| πΎ NoSQL Import | Import converted JSON into MongoDB, Firebase, Elasticsearch, or Postgres jsonb with insertMany() | DevOps, database admins |
| π€ System Interop | Bridge legacy SOAP/enterprise service bus that speaks XML to microservices that speak JSON | Integration engineers |
| π Validation & Audit | Validates well-formedness via DOMParser before conversion β catches missing closing tags or mismatched namespaces early | QA, SEO specialists auditing sitemaps |
| π Learning | Visualizes how tag hierarchy becomes object nesting and how attributes separate from child elements | Students, bootcamps, educators |
For example, an SEO specialist exports sitemap.xml with 2,000 <url> entries; pasting into our XML to JSON converter and clicking Convert to JSON instantly yields {"urlset":{"url":[{"loc":"https://example.com/"},...]}} that can be filtered in JavaScript to find missing images or prioritized routes. A developer integrating a SOAP flight-booking service that returns <Envelope><Body><Flight>... converts it to JSON and feeds it directly to a React component without writing an XML parser. Search terms like xml to json, convert xml to json, xml to json online, xml json converter, xml2json all signal the same friction β making document-heavy XML usable in code-first JSON workflows β which our one-click, private tool resolves.
Features of html-compiler.com XML to JSON Converter
Inspired by htmlbeautifier.org/css's light card design and upgraded for structural conversion, our tool packs everything in one lightweight page β no ads, no server round-trip:
- Triple Input β Paste, Upload, URL: Click Paste via
navigator.clipboard.readText(), Upload any.xml/.svg/.rss/.atom/.xsl/.txtvia FileReader API, or paste a public sitemap/RSS URL and click URL to fetch viafetch()β zero server upload, full privacy. - DOMParser + Recursive Converter β Handles Every XML Construct: Core uses
new DOMParser().parseFromString(xml, 'text/xml')to validate and build a DOM, thenxmlToJson(node)recursively: element nodes collect@attributes, text nodes trimmed to#text, CDATA to#cdata, repeated siblings auto-wrapped as arrays, and text-only elements collapse to plain strings. Supports namespaces, mixed content, and self-closing tags. - Smart Array Handling: When two or more siblings share the same tag name, they become an array automatically. Unique tags stay as objects. Optional Force arrays for all children forces every child value into an array β useful when downstream code always expects
book: [...]even for single items. - Attribute Preservation with Toggle: When Keep attributes is on (default), attributes are stored under
"@attributes":{"id":"bk101","lang":"en"}. Uncheck to ignore attributes for smaller, cleaner output when you only need element text β ideal for simple feeds. - Live Stats & Validation: Input shows Chars / Lines / Size; Output shows Chars / Lines / Keys / Size. Invalid XML shows red error extracting
parsererrormessage with line hint; valid shows green β Valid XML β ready to convert. No silent malformed output. - Pretty Print Control: Toggle Pretty print (2 spaces) for indented
JSON.stringify(obj, null, 2)(readable, diff-friendly) or uncheck for minified single-line JSON for minimal payload. - Copy, Download, Fullscreen: Copy via async Clipboard API with
execCommandfallback, Download asdata.json(Blobapplication/json;charset=utf-8), Full Screen via Fullscreen API on output card for 10,000-line conversions. - 100% Client-Side & Lightweight: No backend, no cookies, no signup. Pure vanilla JS under 10KB, works offline after first load β even on low-SNR or restricted-lab networks.
How to Use XML to JSON Converter β Step-by-Step Guide
Method 1: Paste XML
Copy XML from View Source, Chrome DevTools β Network β Response, Postman, or any editor. Click π Paste (grants clipboard permission) or press Ctrl+V into π₯ Input XML. Stats update live and validator shows green/red banner. Choose options β typically leave Pretty print and Keep attributes checked. Click π Convert to JSON β. Review formatted JSON in π€ Output JSON, then use Copy or Download.
Method 2: Upload File
Click π Upload β select sitemap.xml, feed.rss, pom.xml, drawing.svg or response.xml. FileReader loads it instantly (supports files up to ~5MB, UTF-8, strips BOM). No file ever touches our server. Then convert β ideal for auditing third-party feeds before import.
Method 3: Load from URL
Paste a public XML URL like https://www.w3schools.com/xml/note.xml, https://example.com/sitemap.xml or https://raw.githubusercontent.com/user/repo/main/pom.xml into the URL field and click π URL. We fetch via fetch(url, {mode:'cors'}). If CORS blocks (common on non-CORS feeds), we show actionable guidance: βFetch failed (CORS blocked?) β download file & use Upload instead.β For GitHub, use raw.githubusercontent.com which allows CORS.
After Conversion
Output stats show expanded size β XML to JSON is typically +10β30% due to keys and braces, but -20% if single repeated tags were previously verbose. Use βΆ Full Screen to review deeply nested structures, π Copy to paste into VS Code or Postman (test with JSON.parse), or β¬ Download to get data.json for MongoDB/Node import. Validate result with our JSON Beautifier or feed into JSON to CSV.
Pro tip: Press Ctrl + Enter to convert instantly without mouse β same shortcut as our beautifiers for muscle memory.
Understanding the Conversion: XML Constructs β JSON Mapping
Our DOMParser + recursive xmlToJson handles edge cases that naive regex converters miss:
| XML Pattern | Raw XML | JSON After Convert |
|---|---|---|
| Simple element | <title>XML Guide</title> | "title": "XML Guide" |
| Attributes | <book id="bk101" lang="en"> | "book":{"@attributes":{"id":"bk101","lang":"en"}} |
| Attributes + text | <price currency="USD">44.95</price> | "price":{"@attributes":{"currency":"USD"},"#text":"44.95"} |
| Repeated siblings | <book>...</book><book>...</book> | "book": [{...}, {...}] (array) |
| CDATA | <![CDATA[ <b>bold</b> ]]> | "#cdata": " <b>bold</b> " |
| Mixed content | <p>Hello <b>world</b> !</p> | {"#text":"Hello !","b":"world"} |
| Empty/self-closing | <item id="1" /> | "item":{"@attributes":{"id":"1"}} |
// core logic
function xmlToJson(node, keepAttrs, forceArray){
let obj = {};
if(node.nodeType===1 && keepAttrs && node.attributes.length){
obj["@attributes"]={};
for(let a of node.attributes) obj["@attributes"][a.name]=a.value;
}
for(let child of node.childNodes){
if(child.nodeType===3){ // text
let t=child.nodeValue.trim();
if(t) obj["#text"]=(obj["#text"]?obj["#text"]+" ":"")+t;
} else if(child.nodeType===4){ // CDATA
obj["#cdata"]=child.nodeValue;
} else if(child.nodeType===1){
let name=child.nodeName;
let val=xmlToJson(child, keepAttrs, forceArray);
if(obj[name]===undefined) obj[name]= forceArray? [val] : val;
else {
if(!Array.isArray(obj[name])) obj[name]=[obj[name]];
obj[name].push(val);
}
}
}
// collapse text-only element to string
let keys=Object.keys(obj);
if(keys.length===1 && keys[0]==="#text") return obj["#text"];
if(keys.length===0) return "";
return obj;
}
Options: Pretty print toggles JSON.stringify(data,null,2) vs JSON.stringify(data) (minified). Keep attributes includes/excludes @attributes. Force arrays wraps every child value as array for schema stability β handy when your API contract always expects items: [...] even with one item, avoiding if (!Array.isArray(...)) checks.
Before vs After Example β XML to JSON in Action
| Before (XML β 14 lines) | After JSON (Pretty 2-space) |
|---|---|
| <?xml version="1.0"?> <catalog> <book id="bk101"> <author>Gambardella</author> <title>XML Guide</title> <price>44.95</price> </book> <book id="bk102"> <author>Ralls, Kim</author> <title>Midnight Rain</title> </book> </catalog> | { "catalog": { "book": [ { "@attributes": { "id": "bk101" }, "author": "Gambardella", "title": "XML Guide", "price": "44.95" }, { "@attributes": { "id": "bk102" }, "author": "Ralls, Kim", "title": "Midnight Rain" } ] } } |
XML vs JSON β Key Differences & When to Use Each
| Aspect | XML | JSON |
|---|---|---|
| Structure | Tags <book>, attributes, namespaces, strict hierarchy, one root | Objects {}, arrays [], keys always strings, no attributes |
| Verbosity | High β opening + closing tags, repeated names | ~40% smaller, lighter payload |
| Types | All text β numbers/booleans inferred by schema | Typed: string, number, boolean, null, object, array |
| Comments/CDATA | Yes <!-- --> and <![CDATA[ ]]> | No comments (strict), CDATA becomes string |
| Parsing | DOMParser, stricter, heavier | JSON.parse β fast, native to JS |
| Best For | Sitemaps, RSS/Atom, SOAP, SVG, Office, Maven | REST APIs, SPAs, MongoDB, config, mobile |
| Ideal conversion | Document β | β Programmable data |
If you consume modern REST APIs (GitHub, Stripe, OpenAI) you live in JSON β use JSON Beautifier after converting. If you handle SOAP, RSS, sitemaps, SVG, or Java configs, start with XML to JSON to make them code-ready. Many enterprise stacks use both β legacy SOAP backbone with JSON microservices on top β bookmark both tools.
Pro Tips, Common Pitfalls & Browser Compatibility
Expert Tips
- Single root required: XML must have exactly one root element. Fragments like
<a>1</a><b>2</b>are invalid β wrap in<root>before convert. Validator will flag Extra content at end of document. - Preserve leading zeros & types: All values stay strings (
"007"stays"007", not7) to preserve ZIP codes, IDs, and codes. Convert to numbers in JS withNumber()only where needed β avoid losing00123. - Force arrays for stable schemas: Check Force arrays when your consumer always expects an array (e.g.,
books: [...]) even for singletons β preventsobject vs arraybranching bugs. - Large files >500KB: Use Download after convert rather than Copy β clipboard may lag. Fullscreen helps scan 10k-entry sitemaps.
- CDATA & entities:
&decodes to&,<to<via DOMParser β expected. CDATA<![CDATA[<html>]]>is preserved under#cdatawithout parsing. - Namespace awareness: Tag names include prefix as-is like
svg:circle,media:thumbnailβ no collapsing. Good for RSSmedia:contentfeeds.
Common Errors Our Validator Catches
| Invalid XML | Error Shown | Fix |
|---|---|---|
<book>...<book> | Opening and ending tag mismatch | Close with </book> |
<root></root> <extra> | Extra content at end of document | Single root only β wrap fragments |
<tag>A & B</tag> | Entity not defined / stray & | Escape as A & B |
<note><to>A</from> | Mismatched tag: to vs from | Match closing tag name |
| Empty input | Input is empty | Paste XML first |
Browser compatibility: Chrome 60+, Firefox 55+, Safari 11+, Edge 79+ β uses only DOMParser, JSON, Clipboard, FileReader, Fetch, Fullscreen, and Blob APIs with graceful fallbacks. XML 1.0 compliant including namespaces, CDATA, comments, processing instructions, and UTF-8/BOM.
Frequently Asked Questions (FAQ)
What is XML to JSON converter and how does it work?
XML to JSON converter parses XML with DOMParser and recursively maps the DOM tree to JSON. Text-only elements become strings, elements with attributes get @attributes, repeated siblings become arrays, CDATA becomes #cdata, and mixed text becomes #text. Final JSON is JSON.stringify(obj, null, 2) for pretty print or JSON.stringify(obj) for minified.
How do I convert XML to JSON with attributes?
Keep Keep attributes checked (default). <book id="bk101" lang="en"><title>A</title></book> becomes {"book":{"@attributes":{"id":"bk101","lang":"en"},"title":"A"}}. Uncheck to drop attributes for smaller output.
Why do repeated tags become arrays?
To avoid data loss. XML allows many <item> siblings; JSON objects cannot have duplicate keys. The converter detects duplicates and promotes the value to an array: one <book> β object, two+ <book> β [object, object]. Use Force arrays to always get array even for one item.
What about CDATA, namespaces and comments?
CDATA <![CDATA[ ... ]]> is preserved as #cdata. Namespaced tags like media:thumbnail or svg:circle keep their prefix as key name. Comments <!-- --> are ignored (not in DOM text). Processing instructions are skipped.
Is this XML to JSON converter free and safe for private data?
100% safe β all processing is client-side. No XML is sent to servers, no logs, no cookies. Disconnect internet after load and it still converts. For ultra-sensitive SOAP payloads with tokens/PII, clear Input after download.
How is XML to JSON different from XML Beautifier?
XML Beautifier reformats XML for readability (indent 2 spaces) but stays XML. XML to JSON changes the data model from tag-based to object-based for code use. Use Beautifier to audit sitemap.xml visually; use XMLβJSON to import it into JavaScript, MongoDB, or Sheets.
Can I convert large XML files or load from URL?
Yes β supports files up to ~5MB via Upload and URLs via CORS fetch. For >50k elements, use Download instead of Copy. If URL fetch fails due to CORS, download the file and use Upload β the most reliable for sitemaps/feeds on non-CORS hosts.
Best XML to JSON Converter Online Free in 2026 β Convert Now
Whether you are a developer bridging SOAP XML to REST JSON, an SEO auditing sitemaps and RSS feeds, or a student learning data formats, a reliable XML to JSON converter turns hours of manual DOM walking into one click. Stop writing throwaway scripts to handle @attributes and repeated tags β paste your XML above, hit Convert to JSON, and get clean, validated, pretty-printed JSON you can paste into VS Code, send to MongoDB, or import to Sheets via JSON to CSV. Bookmark html-compiler.com/xml-to-json/ β the lightweight, private, evergreen xml to json, convert xml to json, xml json converter tool for 2026 and beyond. Explore: XML Beautifier β’ JSON Beautifier β’ CSV to JSON β’ HTML Beautifier β’ HTML Compiler β all client-side, all free forever.