XML Tutorial · XML in the Real World · Lesson 27 of 28
XML vs JSON vs YAML
How XML, JSON and YAML compare, how to convert between XML and JSON without losing information, and how to choose a format.
Side by side
<order id="1042"><customer>Ada</customer><item qty="2">Tea</item><item qty="1">Mug</item></order>
{"id": 1042, "customer": "Ada", "items": [{"name": "Tea", "qty": 2}, {"name": "Mug", "qty": 1}]}
id: 1042
customer: Ada
items:
- {name: Tea, qty: 2}
- {name: Mug, qty: 1}
| XML | JSON | YAML | |
|---|---|---|---|
| Data types | Text (types come from a schema) | String, number, boolean, null, object, array | Like JSON, plus dates and more |
| Comments | Yes | No | Yes |
| Attributes vs children | Both | Only properties | Only keys |
| Mixed content (documents) | Natural | Awkward | Awkward |
| Schema and validation | DTD, XSD, RELAX NG, Schematron | JSON Schema | JSON Schema (usually) |
| Query and transform | XPath, XSLT, XQuery | JSONPath, jq | Converted to JSON first |
| Namespaces | Yes | No | No |
| Size and verbosity | Largest | Small | Smallest to type |
| Typical use | Documents, standards-based exchange, enterprise, Office/SVG | Web APIs, configuration | Configuration (Kubernetes, CI) |
Converting XML to JSON
There is no single correct mapping: you must decide how attributes, repeated elements, text and types become JSON. Write the mapping explicitly for your data:
import json
from lxml import etree
order = etree.fromstring(b'<order id="1042"><customer>Ada</customer><item qty="2">Tea</item><item qty="1">Mug</item></order>')
data = {
"id": int(order.get("id")),
"customer": order.findtext("customer"),
"items": [{"name": i.text, "qty": int(i.get("qty"))} for i in order.findall("item")],
}
print(json.dumps(data, separators=(",", ":")))
Output
{"id":1042,"customer":"Ada","items":[{"name":"Tea","qty":2},{"name":"Mug","qty":1}]}<?php
$order = simplexml_load_string('<order id="1042"><customer>Ada</customer><item qty="2">Tea</item><item qty="1">Mug</item></order>');
$data = [
"id" => (int) $order['id'],
"customer" => (string) $order->customer,
"items" => [],
];
foreach ($order->item as $item) {
$data["items"][] = ["name" => (string) $item, "qty" => (int) $item['qty']];
}
echo json_encode($data), "\n";
Output
{"id":1042,"customer":"Ada","items":[{"name":"Tea","qty":2},{"name":"Mug","qty":1}]}import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.*;
import java.io.ByteArrayInputStream;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
String xml = "<order id=\"1042\"><customer>Ada</customer><item qty=\"2\">Tea</item><item qty=\"1\">Mug</item></order>";
Element order = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new ByteArrayInputStream(xml.getBytes("UTF-8"))).getDocumentElement();
List<String> items = new ArrayList<>();
NodeList nodes = order.getElementsByTagName("item");
for (int i = 0; i < nodes.getLength(); i++) {
Element item = (Element) nodes.item(i);
items.add("{\"name\":\"" + item.getTextContent() + "\",\"qty\":" + Integer.parseInt(item.getAttribute("qty")) + "}");
}
String customer = order.getElementsByTagName("customer").item(0).getTextContent();
System.out.println("{\"id\":" + Integer.parseInt(order.getAttribute("id")) + ",\"customer\":\"" + customer
+ "\",\"items\":[" + String.join(",", items) + "]}");
}
}
Output
{"id":1042,"customer":"Ada","items":[{"name":"Tea","qty":2},{"name":"Mug","qty":1}]}Run this on your computer — see “Get Started” for setup.
In real Java code use Jackson (jackson-dataformat-xml) instead of building JSON by hand; the hand-written
version above only keeps the example free of dependencies.
Generic converters (Python's xmltodict, or PHP's json_encode(simplexml_load_string(...))) are quick but lossy
and inconsistent: one <item> becomes an object while two become an array, and every value is a string.
Choosing
- Public web or mobile API: JSON.
- Configuration edited by people: YAML or TOML (JSON if it's generated).
- Documents with markup, standards that mandate XML (finance, healthcare, government, publishing), strict schema-validated contracts, or XSLT pipelines: XML.
- Don't convert working XML integrations to JSON for fashion; do validate whatever you accept.
Test yourself
Which is a reason to prefer XML over JSON?
Documents with mixed content and markupSmaller payloadsNative number typesBrowser APIs return JSON
Show answer
Answer: Documents with mixed content and markup
XML handles text interleaved with markup naturally; JSON is better for plain data structures.