XML to JSON β€” Convert XML to JSON Online

Free XML to JSON converter β€” paste XML, upload .xml file or load from URL and convert to valid JSON instantly via DOMParser. Handles attributes, nested elements, repeated tags as arrays, CDATA & text nodes. Client-side, instant, no signup.

✨ DOMParser β€’ Recursive JSONπŸ“₯ Paste / Upload / URLπŸ“‹ Copy & ⬇ Downloadβ›Ά Full Screen⚑ 100% Client-Side

πŸ“₯ Input XML

Chars: 0 β€’ Lines: 0 β€’ Size: 0 B
βœ“ Valid XML β€” ready to convert
DOMParser β€’ recursive β€’ arrays for repeats

πŸ“€ Output JSON

Chars: 0 β€’ Lines: 0 β€’ Keys: 0 β€’ Size: 0 B

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.

BenefitHow XML to JSON HelpsWho Benefits Most
πŸ”Œ API ModernizationTurn SOAP XML responses into JSON that React, Node.js, and fetch can JSON.parse immediately β€” no XML parser in app codeFrontend & backend developers
πŸ“Š Data AnalysisLoad sitemap or RSS XML into Python pandas, Jupyter, or BI tools after converting to JSON/CSV pipelineData engineers, analysts
⚑ JavaScript NativeJSON is directly assignable as const data = {...} and supports map/filter/reduce without DOM traversalJS/TS, React, Next.js developers
πŸ’Ύ NoSQL ImportImport converted JSON into MongoDB, Firebase, Elasticsearch, or Postgres jsonb with insertMany()DevOps, database admins
🀝 System InteropBridge legacy SOAP/enterprise service bus that speaks XML to microservices that speak JSONIntegration engineers
πŸ” Validation & AuditValidates well-formedness via DOMParser before conversion β€” catches missing closing tags or mismatched namespaces earlyQA, SEO specialists auditing sitemaps
πŸŽ“ LearningVisualizes how tag hierarchy becomes object nesting and how attributes separate from child elementsStudents, 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:

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 PatternRaw XMLJSON 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

AspectXMLJSON
StructureTags <book>, attributes, namespaces, strict hierarchy, one rootObjects {}, arrays [], keys always strings, no attributes
VerbosityHigh β€” opening + closing tags, repeated names~40% smaller, lighter payload
TypesAll text β€” numbers/booleans inferred by schemaTyped: string, number, boolean, null, object, array
Comments/CDATAYes <!-- --> and <![CDATA[ ]]>No comments (strict), CDATA becomes string
ParsingDOMParser, stricter, heavierJSON.parse β€” fast, native to JS
Best ForSitemaps, RSS/Atom, SOAP, SVG, Office, MavenREST APIs, SPAs, MongoDB, config, mobile
Ideal conversionDocument β†’β†’ 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

Common Errors Our Validator Catches

Invalid XMLError ShownFix
<book>...<book>Opening and ending tag mismatchClose with </book>
<root></root> <extra>Extra content at end of documentSingle root only β€” wrap fragments
<tag>A & B</tag>Entity not defined / stray &Escape as A &amp; B
<note><to>A</from>Mismatched tag: to vs fromMatch closing tag name
Empty inputInput is emptyPaste 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.