XML Tutorial · XML Basics · Lesson 1 of 28
XML Introduction
What XML is, what it's used for today, how it differs from HTML and JSON, and how to read and write it in Python, PHP and Java.
What is XML?
XML (eXtensible Markup Language) is a text format for structured data. You invent the tags that describe your data, nest them into a tree, and any XML parser in any language can read the result:
<?xml version="1.0" encoding="UTF-8"?>
<order id="1042">
<customer>Ada Lovelace</customer>
<item sku="TEA-01" qty="2">Green tea</item>
<item sku="MUG-07" qty="1">Camel mug</item>
</order>
XML became a W3C standard in 1998 and is still everywhere, often out of sight:
- Documents: Word (
.docx), Excel (.xlsx) and PowerPoint files are zipped XML; so are EPUB books and SVG images. - Configuration: Maven
pom.xml, Android manifests, .NET project files, Spring and many enterprise tools. - Integration: SOAP web services, banking (ISO 20022 payment messages), healthcare (HL7 CDA), e-invoicing (UBL), government and publishing (DocBook, DITA, JATS).
- The web: RSS and Atom feeds, sitemaps (
sitemap.xml) and XHTML.
XML vs HTML vs JSON
| XML | HTML | JSON | |
|---|---|---|---|
| Purpose | Describe any data or document | Display web pages | Exchange data between programs |
| Tags | You define them | Fixed set (<p>, <div>) |
No tags: objects and arrays |
| Strictness | Must be well-formed or parsing fails | Browsers repair mistakes | Must be valid JSON |
| Schemas | DTD, XSD, RELAX NG, Schematron | No | JSON Schema |
| Query and transform | XPath, XSLT, XQuery | CSS selectors | JSONPath, jq |
| Mixed content (text with markup) | Yes | Yes | Awkward |
Reading XML in code
The same task in three languages: parse the order above and list its items. Python uses lxml, PHP its built-in SimpleXML, Java the DOM parser that ships with the JDK. Switch tabs to compare; Python and PHP run in your browser.
from lxml import etree
xml = b"""<order id="1042">
<customer>Ada Lovelace</customer>
<item sku="TEA-01" qty="2">Green tea</item>
<item sku="MUG-07" qty="1">Camel mug</item>
</order>"""
order = etree.fromstring(xml)
print("Order", order.get("id"), "for", order.findtext("customer"))
for item in order.findall("item"):
print(f"- {item.get('qty')} x {item.text} ({item.get('sku')})")
Output
Order 1042 for Ada Lovelace - 2 x Green tea (TEA-01) - 1 x Camel mug (MUG-07)
<?php
$xml = '<order id="1042">
<customer>Ada Lovelace</customer>
<item sku="TEA-01" qty="2">Green tea</item>
<item sku="MUG-07" qty="1">Camel mug</item>
</order>';
$order = simplexml_load_string($xml);
echo "Order {$order['id']} for {$order->customer}\n";
foreach ($order->item as $item) {
echo "- {$item['qty']} x {$item} ({$item['sku']})\n";
}
Output
Order 1042 for Ada Lovelace - 2 x Green tea (TEA-01) - 1 x Camel mug (MUG-07)
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.*;
import java.io.ByteArrayInputStream;
public class Main {
public static void main(String[] args) throws Exception {
String xml = """
<order id="1042">
<customer>Ada Lovelace</customer>
<item sku="TEA-01" qty="2">Green tea</item>
<item sku="MUG-07" qty="1">Camel mug</item>
</order>""";
Element order = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new ByteArrayInputStream(xml.getBytes("UTF-8"))).getDocumentElement();
String customer = order.getElementsByTagName("customer").item(0).getTextContent();
System.out.println("Order " + order.getAttribute("id") + " for " + customer);
NodeList items = order.getElementsByTagName("item");
for (int i = 0; i < items.getLength(); i++) {
Element item = (Element) items.item(i);
System.out.println("- " + item.getAttribute("qty") + " x " + item.getTextContent()
+ " (" + item.getAttribute("sku") + ")");
}
}
}
Output
Order 1042 for Ada Lovelace - 2 x Green tea (TEA-01) - 1 x Camel mug (MUG-07)
Run this on your computer — see “Get Started” for setup.
JavaScript in the browser has XML built in too (DOMParser); the XML in JavaScript
page has live examples.
What this tutorial covers
- Basics: syntax, elements and attributes, well-formedness, special characters, namespaces.
- Validation: DTDs, XML Schema (XSD), RELAX NG and Schematron.
- Querying and transforming: XPath, XSLT and XQuery.
- XML in code: Python, PHP, Java and JavaScript; DOM vs streaming; security (XXE).
- XML in the real world: SOAP, feeds and sitemaps, SVG and Office files, and when to choose XML, JSON or YAML.
Test yourself
Which of these is a key difference between XML and HTML?
In XML you define your own tagsXML can only store numbersHTML must be well-formedXML has no attributes
Show answer
Answer: In XML you define your own tags
HTML has a fixed vocabulary for web pages; XML is a meta-language for defining your own.