XML vs JSON

If you've been through this site's JavaScript course, JSON will already feel familiar. Both formats structure data, both are text-based and human-readable, and both are still very much in active use — just for different things.

The same data, both ways

XML book.xml
<book id="42" language="en">
  <title>Dune</title>
  <genre>Science Fiction</genre>
  <genre>Adventure</genre>
</book>
JSON book.json
{
  "id": 42,
  "language": "en",
  "title": "Dune",
  "genres": ["Science Fiction", "Adventure"]
}

The JSON version is shorter — no closing tag repeating the element name, no attribute-vs-element decision to make. That brevity is a big part of why JSON became the default choice for web APIs.

What JSON gave up

JSON has no real equivalent for a few things XML does natively. It has no concept of attributes — everything is just a key. It has no built-in namespace mechanism for safely combining vocabularies. It can't represent mixed content — text and elements interleaved, like a paragraph of HTML containing a <strong> tag partway through a sentence — which is exactly the kind of thing XML (and HTML, which is itself a flavor of markup in the same family) was designed to handle well. And JSON has no standardized, built-in validation language as mature as DTDs or XML Schema.

What XML gave up in return

None of that comes free. XML documents are more verbose to write and slower to parse than the equivalent JSON. Every value needs an opening and closing tag; JSON's objects and arrays map far more directly onto the data structures most programming languages already use, which made it a natural fit once JavaScript-heavy web apps needed to move data between browser and server constantly.

Where you still meet XML today

Despite JSON's dominance in REST APIs, XML remains the format underneath a long list of things still running in production: Microsoft Office file formats (a .docx or .xlsx is a zip file full of XML), SOAP-based web services still common in banking and enterprise integration, RSS/Atom feeds, Android app layout files, SVG images, and countless configuration formats and industry-specific data-interchange standards (healthcare, finance, and government systems in particular lean heavily on strictly validated XML). If you work in any of those spaces, XML isn't legacy — it's the format you'll be reading and writing regularly.

Course complete: that covers XML from top to bottom — self-describing tags, elements versus attributes, the one-root-element rule, the strict well-formedness rules that make XML predictable to parse, DTDs for validating structure, namespaces for safely combining vocabularies, XPath for querying a document, and finally how XML compares to JSON. Between the two, you now know when each format is actually the right tool for the job — not just the one you happen to already know.