16. XML and JSON Compared
What you will learn
- How the same data looks in XML and in JSON
- The strengths and weaknesses of each
- How to read both in JavaScript and PHP
- How to choose between them
Two ways to carry data
Both XML and JSON are text formats for storing and exchanging data. Both are readable by people and by programs, and both are independent of any one programming language. They differ in style and in what they are best at.
The same data in both
XML code
<?xml version="1.0" encoding="UTF-8"?>
<person id="101">
<name>Sam Rivera</name>
<age>25</age>
<student>true</student>
<skills>
<skill>HTML</skill>
<skill>CSS</skill>
</skills>
</person>
JSON code
{
"id": 101,
"name": "Sam Rivera",
"age": 25,
"student": true,
"skills": ["HTML", "CSS"]
}
What you can see at once
- JSON is shorter. XML repeats every name in a closing tag.
- JSON has real types (numbers, booleans, arrays). In XML,
25andtrueare just text until a schema says otherwise. - JSON has a direct array. XML shows a list by repeating elements.
- XML has attributes (
id="101") and JSON does not, so JSON stores them as ordinary fields.
Side-by-side comparison
| XML | JSON | |
|---|---|---|
| Size | More verbose | Compact |
| Reading in JavaScript | Needs a parser and DOM code | One call: JSON.parse() |
| Data types | All text, unless a schema is used | String, number, boolean, null, array, object |
| Comments | Allowed | Not allowed |
| Attributes and mixed content | Yes. Good for documents with text and markup | No |
| Namespaces | Built in | None |
| Validation | DTD and XML Schema, very mature | JSON Schema (a separate standard) |
| Transformation and querying | XPath, XSLT, XQuery | Language features, and tools such as JSONPath |
| Ordering of items | Document order is meaningful | Arrays are ordered. Object key order should not be relied on |
| Typical use | Documents, feeds, sitemaps, configuration, enterprise systems | Web and mobile APIs, settings, data in JavaScript apps |
Reading the same data in JavaScript
Example
<pre id="demo"></pre>
<script>
const jsonText = '{"name":"Sam Rivera","age":25,"skills":["HTML","CSS"]}';
const xmlText = `<person><name>Sam Rivera</name><age>25</age>
<skills><skill>HTML</skill><skill>CSS</skill></skills></person>`;
// JSON: one step
const fromJson = JSON.parse(jsonText);
// XML: parse, then pull out each value
const xml = new DOMParser().parseFromString(xmlText, "application/xml");
const fromXml = {
name: xml.querySelector("name").textContent,
age: Number(xml.querySelector("age").textContent),
skills: Array.from(xml.querySelectorAll("skill")).map(function (s) { return s.textContent; })
};
document.getElementById("demo").textContent =
"JSON: " + JSON.stringify(fromJson) + "\nXML: " + JSON.stringify(fromXml);
</script>
Output (after the script runs)
JSON: {"name":"Sam Rivera","age":25,"skills":["HTML","CSS"]}
XML: {"name":"Sam Rivera","age":25,"skills":["HTML","CSS"]}
Both end up as the same JavaScript object. The JSON route took one line. The XML route needed code to find each value and to convert the age from text to a number.
Converting between them in PHP
PHP can convert in either direction. Plain conversion of arbitrary XML to JSON loses information, so treat it as a shortcut for simple data only.
PHP code
<?php
$xml = simplexml_load_string("<person><name>Sam</name><age>25</age></person>");
echo json_encode($xml) . "<br>";
$data = json_decode('{"name":"Sam","age":25}', true);
echo $data["name"] . " is " . $data["age"];
Output
{“name”:”Sam”,”age”:”25″}
Sam is 25
Notice the first result: the age came out as the string "25", because XML has no number type. Also, a repeated element may become an array, but a single one becomes a plain value, so the shape can change with the data. Write explicit conversion code when the format matters.
What does not convert cleanly
- Attributes versus child elements: JSON has no difference, so a convention is needed.
- Mixed content (text with tags inside) has no natural JSON form.
- Comments, namespaces, and processing instructions are lost.
- Single and repeated elements: one
skillis not clearly a list. - Types: XML text must be converted to numbers and booleans on purpose.
When to choose XML
- You are marking up documents, where text and tags are mixed.
- You must follow an existing standard that uses XML, such as RSS, Atom, sitemaps, SVG, or many industry formats.
- You need namespaces, strong schema validation, or XSLT.
- You work with older or enterprise systems and long-lived archives.
When to choose JSON
- You are building a web or mobile API.
- The data is simple lists and records, used mainly by JavaScript.
- You want small payloads and quick parsing.
- You store settings, or exchange data between your own services.
Other formats you may meet
YAML and TOML are popular for human-edited configuration files. CSV suits plain tables. Protocol Buffers and similar binary formats suit very fast, compact exchange between services. There is no single best format, only the right tool for the job.
Security: the same rules apply
Whichever you choose, data from outside is untrusted. Validate its structure and values, escape it when you print it, never build queries or file paths from it, and use the safe parsing options of your library. XML adds the extra risks you met in the DTD lesson (external entities), so disable those for untrusted input.
Common mistakes
- Choosing a format by habit instead of by need.
- Expecting XML values to be numbers and booleans automatically.
- Converting XML to JSON blindly and losing attributes or mixed content.
- Believing that either format is “more secure”. Safety comes from how you handle the data.
- Treating JSON object key order as dependable.
Exercise
Write this product in both formats: id p-7 (an attribute in XML), name Notebook, price 4.5, in stock (true), and two tags, paper and school.
Show solution
<product id="p-7">
<name>Notebook</name>
<price>4.5</price>
<inStock>true</inStock>
<tags>
<tag>paper</tag>
<tag>school</tag>
</tags>
</product>
{
"id": "p-7",
"name": "Notebook",
"price": 4.5,
"inStock": true,
"tags": ["paper", "school"]
}
In JSON the price is a real number and the stock value a real boolean. In XML both are text.
Knowledge check
1. Which format has built-in number and boolean types?
JSON.
2. Name two situations where XML is the better choice.
For example: marking up documents with mixed text, following a standard such as RSS or SVG, or needing namespaces, schemas, or XSLT.
3. What is lost when you convert XML to JSON without care?
Attributes, mixed content, comments, namespaces, and the distinction between a single element and a list.
Summary
- XML is richer and stricter, while JSON is shorter and easier to use in JavaScript.
- Choose XML for documents, standards, and schema-heavy work, and JSON for most web APIs.
- Convert with care, and treat data from outside as untrusted in both formats.