XML and JSON both represent hierarchical data, and while JSON dominates modern REST APIs and front-end web apps, XML remains deeply embedded in enterprise systems: SOAP web services, RSS and Atom feeds, SEO sitemaps, SVG graphics, Maven/Android configs, Microsoft Office (.xlsx/.docx) internals, e-invoicing (GST/UBL), and banking protocols (ISO 20022). Converting between XML and JSON is a routine integration task — and far trickier than a simple syntax swap because the two formats have fundamentally different data models. This guide compares both side by side, explains every conversion edge case, and gives a practical checklist for round-tripping XML, JSON, and CSV safely.

The same order record in XML and JSON

<?xml version="1.0" encoding="UTF-8"?>
<order id="1042" currency="INR">
  <customer>Asha Rao</customer>
  <item sku="A1" qty="2">Notebook</item>
  <item sku="B7" qty="1">Pen</item>
</order>
{
  "order": {
    "@id": 1042,
    "@currency": "INR",
    "customer": "Asha Rao",
    "item": [
      { "@sku": "A1", "@qty": 2, "#text": "Notebook" },
      { "@sku": "B7", "@qty": 1, "#text": "Pen" }
    ]
  }
}

Side-by-side comparison

DimensionXMLJSON
Data modelDocument tree: elements, attributes, text nodes, comments, namespacesData structures: objects, arrays, strings, numbers, booleans, null
Native typesText only (types come from an external XSD schema)Strings, numbers, booleans, null, arrays, objects
ArraysImplicit (repeated sibling tags with the same name)Explicit ([…]) — 0, 1, or many items share one shape
CommentsBuilt-in (<!-- comment -->)Not allowed in RFC 8259
Payload sizeLarger (closing tags repeat every element name)Compact, fast to parse natively in JavaScript
Mixed contentFirst-class (<p>Hi <b>Asha</b></p>)Awkward — requires verbose AST arrays
Schemas & validationXSD, RelaxNG, XSLT, XPath, XML-DSigJSON Schema, Zod, TypeScript types

Six conversion pitfalls that break integrations

  1. The single-element array trap. In XML, two <item> elements convert to a JSON array ("item": [{…}, {…}]), whereas an order with one <item> converts to a single JSON object ("item": {…})! Code calling order.item.map(…) works on multi-item orders and crashes in production on single-item orders. Always normalise repeatable elements in your code: const items = Array.isArray(order.item) ? order.item : order.item ? [order.item] : [];.
  2. Attributes vs child elements. JSON has no attribute concept. Converters adopt conventions — SnipFerry uses @attr for attributes and #text for text content when an element has both attributes and text — so converting back to XML preserves the original distinction.
  3. Leading zeros and big IDs under type coercion. Every XML value starts as text. Auto-parsing numbers turns qty="2" into numeric 2, which is convenient — until a postal code "00501" turns into 501 or a 19-digit invoice ID loses precision in IEEE-754 floating point. Turn off Parse numeric values in XML to JSON whenever your feed contains leading-zero codes or 64-bit IDs.
  4. Namespaces (xmlns and prefixes). SOAP and Atom documents qualify tags with prefixes like soap:Body or dc:creator. Simple converters keep the prefix inside the JSON key name and preserve @xmlns attributes on round-trip.
  5. Invalid XML element names from JSON keys. JSON keys can contain spaces, start with digits ("2026_sales"), or hold special symbols. XML tag names must start with a letter or underscore and cannot contain spaces, so JSON to XML sanitises invalid characters when exporting.
  6. Empty elements vs null vs empty string. Does <discount/> mean "", null, or {}? Document your convention up front when mapping XML feeds into strongly typed code (see Generate Types from JSON).

Converting XML to JSON (and JSON to XML) in your browser

  • XML to JSON: Parses XML using your browser’s native XML parser, validates syntax with line/column errors, and lets you toggle attribute preservation (@attr) and numeric parsing.
  • JSON to XML: Wraps JSON objects or arrays in a customisable root tag, optionally emits the <?xml version="1.0" encoding="UTF-8"?> declaration, and turns @attr / #text keys back into proper XML attributes and text nodes.

When XML is actually a flat table: XML ↔ CSV

Many legacy exports — product catalogues, sitemap URLs, RSS feeds, bank statements — are simply repeated XML records with identical child fields. Instead of converting XML → JSON → CSV in two steps, drop the XML file straight into XML to CSV to flatten repeating elements and attributes into spreadsheet rows ready for Excel or the CSV Analyzer. Going the other way, CSV to XML generates clean indented XML with your choice of root and row tag names.

Which format should you choose for new projects?

Pick JSON for new REST APIs, webhooks, browser/mobile apps, and NoSQL document stores: it is smaller on the wire, maps directly onto JavaScript/Python/Go data structures, and pairs naturally with JSON Schema and OpenAPI. Stick with XML when working with document-centric mixed markup (publishing, SVG, Office formats), standards that mandate XML digital signatures (XML-DSig) or XSD validation, or legacy enterprise gateways. When integrating with an external XML provider, convert and validate once at your service boundary so internal code works cleanly with typed JSON.

Security note: XXE attacks

Server-side XML parsers with external entities enabled are vulnerable to XML External Entity (XXE) attacks, where a malicious <!DOCTYPE> declaration tricks the server into reading local files (/etc/passwd) or probing internal cloud metadata endpoints (SSRF). Always disable DTDs and external entity resolution in server XML libraries. JSON has no DTD or external-entity mechanism, which is a major reason modern APIs prefer it. Comparing other config and data formats? Read YAML vs JSON vs TOML and JSON vs CSV.