XML (eXtensible Markup Language) has been a cornerstone of data exchange since the late 1990s. While JSON has become the dominant format for web APIs, XML remains essential in enterprise systems, document formats (DOCX, SVG, RSS), configuration files, and protocols like SOAP and XMPP. Understanding XML structure, namespaces, and validation is still a critical skill for backend developers and system integrators.
This guide covers XML syntax, validation with DTD and XML Schema (XSD), namespaces, XPath querying, and practical formatting tips for debugging XML in modern applications.
XML Structure and Syntax Rules
XML is a strict markup language with a small set of well-formedness rules:
Basic structure:
<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
</book>
</catalog>Key rules:
- Every XML document must have exactly one root element
- All tags must be properly closed (<br /> or <br></br>)
- Tags are case-sensitive (<Book> and <book> are different)
- Attributes must be quoted (id="bk101" not id=bk101)
- Characters <, >, &, ", and ' must be escaped in text content
Escape sequences:
- < for <
- > for >
- & for &
- " for "
- ' for '
A document that follows all these rules is called well-formed. A document that additionally conforms to a schema definition is called valid.
XML Namespaces
Namespaces prevent element name conflicts when combining XML from different vocabularies. They're identified by a URI (not necessarily a real URL) and declared with xmlns:
<?xml version="1.0"?>
<root
xmlns:html="http://www.w3.org/1999/xhtml"
xmlns:svg="http://www.w3.org/2000/svg">
<html:p>A paragraph with HTML namespace</html:p>
<svg:circle cx="50" cy="50" r="30"/>
</root>Default namespace applies to all unprefixed elements:
<root xmlns="http://example.com/myns">
<element>This is in the default namespace</element>
</root>Namespaces are heavily used in:
- SOAP web services (xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/")
- SVG (Scalable Vector Graphics)
- XHTML documents
- Office Open XML (DOCX, XLSX format)
Validation with DTD and XML Schema (XSD)
XML documents can be validated against a schema to ensure they conform to an expected structure.
DTD (Document Type Definition) -- the older, simpler format:
<!-- Internal DTD -->
<!DOCTYPE catalog [
<!ELEMENT catalog (book+)>
<!ELEMENT book (author, title, price)>
<!ATTLIST book id ID #REQUIRED>
<!ELEMENT author (#PCDATA)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT price (#PCDATA)>
]>XSD (XML Schema Definition) -- the modern, more powerful approach:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="catalog">
<xs:complexType>
<xs:sequence>
<xs:element name="book" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="author" type="xs:string"/>
<xs:element name="title" type="xs:string"/>
<xs:element name="price" type="xs:decimal"/>
</xs:sequence>
<xs:attribute name="id" type="xs:ID" use="required"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>XSD supports data types (string, integer, decimal, date, boolean), constraints (minOccurs, maxOccurs, pattern), and inheritance, making it far more expressive than DTD.
XPath: Querying XML Documents
XPath is a query language for navigating XML documents. It's used in XSLT transformations, XML Schema, and directly in code for extracting data.
Basic XPath expressions:
/catalog/book -- All book elements under root catalog
//book -- All book elements anywhere in document
/catalog/book[1] -- First book (XPath uses 1-based indexing!)
/catalog/book[@id] -- Books with an id attribute
/catalog/book[@id='bk101'] -- Book with id=bk101
//book/title/text() -- Text content of all title elements
/catalog/book[price > 40] -- Books with price over 40Using XPath in JavaScript:
const parser = new DOMParser();
const doc = parser.parseFromString(xmlString, 'text/xml');
const result = doc.evaluate(
'//book[@id="bk101"]/title',
doc,
null,
XPathResult.STRING_TYPE,
null
);
console.log(result.stringValue); // "XML Developer's Guide"Using XPath in Python:
from lxml import etree
tree = etree.parse('catalog.xml')
titles = tree.xpath('//book/title/text()') # ['XML Developer's Guide', ...]XML vs JSON: When to Use Each
Choose XML when:
- Working with legacy enterprise systems (SAP, Salesforce, banking APIs still heavily use XML)
- Using SOAP web services
- Handling document-centric formats (DOCX, SVG, RSS/Atom feeds)
- You need mixed content (text + markup, like HTML)
- Validation and schema enforcement is critical
- Working with XSLT transformations
Choose JSON when:
- Building REST APIs
- Working with JavaScript/Node.js frontends
- Data is simple key-value or array structures
- Bandwidth and parsing speed matter
- Human readability in simple structures is important
XML advantages over JSON:
- Comments (<!-- comments -->)
- Attributes vs. elements distinction
- Namespaces (critical for document standards)
- Mature ecosystem: XSLT, XPath, XQuery, XSD
- Mixed content (text nodes mixed with child elements)
JSON advantages:
- Simpler syntax (no closing tags)
- Native JavaScript type support (arrays, booleans, null)
- 30-40% smaller file size for equivalent data
- Easier to read and write by humans
Formatting and Debugging XML
Pretty-printing XML improves readability and is essential for debugging. Compact XML strips all whitespace to minimize file size.
Using our XML Formatter:
Our tool handles both formatting and syntax validation. A red error message indicates where the XML is malformed -- common causes:
- Unclosed tags (missing </tag>)
- Unescaped special characters (& instead of &)
- Mismatched tag names (<Tag> closed with </tag>)
- Invalid attribute quoting (id=abc instead of id="abc")
Command-line formatting:
# xmllint (Linux/macOS):
xmllint --format input.xml > formatted.xml
# Python:
python3 -c "import sys; import xml.dom.minidom; print(xml.dom.minidom.parseString(sys.stdin.read()).toprettyxml(indent=' '))" < input.xml
# Using xmlstarlet:
xmlstarlet fo input.xml > formatted.xmlCommon XML debugging checklist:
1. Check encoding declaration matches actual file encoding
2. Verify all special characters are properly escaped
3. Confirm namespace prefixes are declared
4. Look for byte-order marks (BOM) at file start
5. Check for invalid characters below U+0020 (except tab, CR, LF)