What Is XML?
XML stands for Extensible Markup Language, a markup language designed to store, transport, and structure data in a human-readable, machine-parseable format. XML was defined by the W3C in 1998 (XML 1.0) and updated in 2004 (XML 1.1). Unlike HTML, which defines a fixed set of tags, XML allows authors to define their own tags — the "extensible" in the name.
XML was the dominant data interchange format for web services from the late 1990s through the late 2000s, when JSON's simplicity progressively displaced it for most API use cases. However, XML remains essential in many domains: Microsoft Office (DOCX, XLSX, PPTX), SVG graphics, RSS/Atom feeds, XHTML, SOAP web services, Android layouts, Maven/Gradle build configurations, and countless enterprise integration systems.
Core Syntax
A well-formed XML document:
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="fiction" isbn="978-0-06-112008-4">
<title lang="en">To Kill a Mockingbird</title>
<author>Harper Lee</author>
<year>1960</year>
<price currency="USD">12.99</price>
</book>
<book category="science">
<title lang="en">A Brief History of Time</title>
<author>Stephen Hawking</author>
<year>1988</year>
<price currency="USD">14.99</price>
</book>
</bookstore>
Key concepts:
Elements: Tags that wrap content — <title>To Kill a Mockingbird</title>. Every start tag must have a matching end tag, or use the self-closing form: <br/>.
Attributes: Name-value pairs inside a start tag — category="fiction". Attribute values must be quoted (single or double).
Root element: Every XML document must have exactly one root element that contains all others (here, <bookstore>).
XML Declaration: The optional <?xml version="1.0" encoding="UTF-8"?> processing instruction at the top. Specifying encoding="UTF-8" is highly recommended.
Comments: <!-- This is a comment --> — valid anywhere except inside tags.
CDATA sections: <![CDATA[raw content with <tags> that won't be parsed]]> — for literal content that shouldn't be interpreted as markup.
Well-Formed vs. Valid
XML distinguishes two levels of correctness:
Well-formed — syntactically correct XML:
- Has exactly one root element
- All tags are properly nested (no overlapping)
- All elements are closed
- Attribute values are quoted
- Reserved characters (
<,>,&,",') in content are escaped as entities
Valid — well-formed AND conforming to a schema:
- DTD (Document Type Definition): The original XML schema language, limited but widely supported
- XSD (XML Schema Definition): The standard schema language, supports data types, namespaces, complex constraints
- RELAX NG: A simpler schema language; popular in OASIS standards
- Schematron: Rule-based validation using XPath patterns
Namespaces
XML Namespaces (xmlns) solve the problem of name collisions when combining XML vocabularies from different sources:
<root xmlns:h="http://www.w3.org/1999/xhtml"
xmlns:svg="http://www.w3.org/2000/svg">
<h:div>
<svg:svg width="100" height="100">
<svg:circle cx="50" cy="50" r="40" fill="red"/>
</svg:svg>
</h:div>
</root>
The namespace URI is just an identifier — it doesn't need to point to a real resource. Prefixes (h:, svg:) are aliases for the namespace URIs, and are local to each document. The default namespace (no prefix) is declared with xmlns="...".
XPath and Querying XML
XPath is the standard query language for selecting nodes in an XML document:
/bookstore/book[@category='fiction'] — All fiction books
//book/title — All title elements anywhere
/bookstore/book[price > 13]/title — Books costing more than $13
count(//book) — Number of books
/bookstore/book[last()] — The last book
XQuery extends XPath with FLWOR expressions (For-Let-Where-Order-Return) for complex queries and transformations:
for $book in /bookstore/book
where $book/price > 13
order by $book/year descending
return <result>{$book/title/text()}</result>
XSLT (Extensible Stylesheet Language Transformations) transforms XML into other XML, HTML, or text using template rules:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/bookstore">
<html><body>
<xsl:for-each select="book">
<p><xsl:value-of select="title"/></p>
</xsl:for-each>
</body></html>
</xsl:template>
</xsl:stylesheet>
Character Entities
Five predefined XML entities handle reserved characters in content:
| Character | Entity | Use case |
|---|---|---|
< |
< |
Less-than sign in text content |
> |
> |
Greater-than sign (optional) |
& |
& |
Ampersand in text content |
" |
" |
Double quote in attribute values |
' |
' |
Single quote in attribute values |
DTDs can define additional custom entities.
Common XML-Based Formats
XML serves as the foundation for many specialised formats:
- SVG (Scalable Vector Graphics) — vector images
- XHTML — HTML reformulated as well-formed XML
- RSS/Atom — web feed syndication
- SOAP — Simple Object Access Protocol for web services
- WSDL — Web Services Description Language
- DOCX/XLSX/PPTX — Office Open XML (ZIP containers of XML)
- ODT/ODS/ODP — OpenDocument Format
- Android Layout XML — UI definitions for Android apps
- Maven POM — Java project build configuration (
pom.xml) - Spring XML — Java dependency injection configuration
- XSLT — XML transformation language (itself XML)
- MathML — mathematical notation
- SMIL — multimedia presentation markup
- KML/GML — geographic data formats
XML vs. JSON: When to Use Each
| Scenario | Better choice | Reason |
|---|---|---|
| REST API response | JSON | Simpler, lighter, faster |
| Document-centric data | XML | Mixed content, processing instructions |
| Existing SOAP ecosystem | XML | Protocol requires it |
| Complex schema validation | XML (XSD) | More expressive than JSON Schema |
| SVG graphics | XML | Format requires it |
| Namespace mixing | XML | Built-in namespace support |
| Config files (human-edited) | YAML or TOML | More readable |
| Spreadsheets, presentations | XML (OOXML/ODF) | Format requires it |
Parsing XML
Python (ElementTree and lxml):
import xml.etree.ElementTree as ET
tree = ET.parse('books.xml')
root = tree.getroot()
for book in root.findall('book'):
title = book.find('title').text
price = float(book.find('price').text)
print(f"{title}: ${price}")
# XPath with lxml
from lxml import etree
doc = etree.parse('books.xml')
fiction = doc.xpath("//book[@category='fiction']/title/text()")
JavaScript (DOMParser):
const parser = new DOMParser();
const doc = parser.parseFromString(xmlString, 'application/xml');
const titles = doc.querySelectorAll('title');
titles.forEach(t => console.log(t.textContent));
Converting XML
XML → JSON: Multiple approaches — xmltodict (Python) converts each element to an object; xml2json libraries; manual XSLT transformation. Note: XML's mixed content model (elements + text interleaved) doesn't map cleanly to JSON.
XML → CSV: Only practical for flat, repetitive XML structures. XSLT to produce CSV text, or parsing + flattening in Python/Java.
XML → YAML: Via XML→JSON→YAML pipeline, or direct parsing.
Summary
XML is the elder statesman of structured data formats — verbose, powerful, and ubiquitous in enterprise systems, document standards, and web technologies. Its namespace support, mature schema languages (XSD, RELAX NG, Schematron), rich query ecosystem (XPath, XQuery, XSLT), and ability to mix text with markup make it uniquely suited for document-centric and integration scenarios. JSON has displaced XML for most REST API use cases due to its simplicity, but XML's depth and ecosystem ensure it will remain a foundational technology in computing for decades.
Related conversions
Document conversions that follow this topic naturally: