XML

On this page 7

XML (Extensible Markup Language) is a text-based data format that represents information as a tree of nested elements marked by tags, with optional attributes on each element. Among data formats, it is the classic self-describing, hierarchical format: the tag names travel with the values, so a document such as <invoice><total currency="EUR">120.50</total></invoice> carries both data and its labels.

XML is a W3C recommendation published in 1998 and derived from SGML. It defines only the syntax, not a vocabulary: each industry or application defines its own element names and rules. That flexibility, combined with mature tooling for validation, transformation and querying, explains why XML remains central in publishing, finance, government exchange, office documents and enterprise integration, even where JSON has become the default for web APIs.

How an XML document is built

An XML document consists of an optional XML declaration, exactly one root element, and any number of nested child elements, attributes, text nodes, comments and processing instructions. Every opened element must be closed, element names are case-sensitive, and attribute values must be quoted.

ComponentSyntax examplePurpose
Element<customer>...</customer>Main unit of structure, can contain text and children
Attribute<price currency="USD">Name-value metadata attached to an element
Namespacexmlns:inv="..."Prevents name clashes between vocabularies
CDATA section<![CDATA[ a < b ]]>Text that the parser does not interpret as markup
Entity reference&amp; for an ampersandEscapes reserved characters
XML declaration<?xml version="1.0" encoding="UTF-8"?>States version and character encoding
Core building blocks of XML

A document that follows these syntax rules is well-formed. A document that also conforms to a declared grammar is valid. The distinction matters: any XML parser can confirm well-formedness, but validity requires a schema and tells the receiver that the content has the expected structure.

Validation and the XML tool family

XML is defined as much by its surrounding standards as by its syntax. These companion technologies let organizations specify, check, navigate and transform documents without writing custom code for every format.

StandardRoleTypical use
DTDOriginal grammar language, limited typesLegacy formats, simple document rules
XML Schema (XSD)Strongly typed structural schemaData exchange contracts, financial and public sector messages
RELAX NGCompact, expressive schema languageDocument-oriented vocabularies
XPathExpression language for selecting nodesQuerying and addressing parts of a tree
XSLTRule-based transformation languageConverting XML to HTML, text or other XML
XQueryQuery language over XML collectionsSearching and restructuring document stores
Standards commonly used with XML

Schema validation is the main reason many regulated exchanges still use XML. A receiver can reject a malformed payment message or tax filing automatically, before any business logic runs, and both parties can share the XSD file as the formal contract for the interface.

XML compared with other data formats

XML competes mainly with JSON for data exchange and with columnar formats such as Parquet for analytics. Each format optimizes for a different combination of readability, expressiveness, size and processing speed.

FormatStructureSchema supportTypical strengthTypical weakness
XMLTree with elements, attributes, mixed contentMature: XSD, DTD, RELAX NGValidation, documents with mixed text and markupVerbose, more complex parsing
JSONObjects, arrays, primitive valuesJSON Schema, optionalCompact, native to web APIsNo attributes, comments or mixed content
YAMLIndentation-based maps and listsLimited, usually externalHuman-edited configurationIndentation errors, ambiguous typing
CSVFlat rows and columnsNone built inSimple tabular exchangeNo nesting, inconsistent dialects
ParquetColumnar binary with nested typesEmbedded schemaAnalytical scans and compressionNot human-readable
XML and neighboring formats

One feature remains distinctive: mixed content, where text and markup interleave, as in <p>Pay <b>before</b> Friday</p>. JSON has no natural representation for it, which is why XML still dominates document formats such as office files, technical documentation and legal texts.

Parsing models and performance

Software reads XML with one of two main models. A DOM parser loads the entire document into a tree in memory, which allows random access and XPath queries but can consume several times the file size in memory. A streaming parser such as SAX or StAX reads the document as a sequence of events and keeps memory use roughly constant.

  • Use DOM parsing for configuration files, messages and documents of up to a few megabytes that need navigation or modification.
  • Use streaming parsing for large exports, feeds and logs that can reach gigabytes, where loading the whole tree would exhaust memory.
  • Compress XML in transit with gzip, because its repetitive tag names compress very well.
  • Convert XML to a columnar format when the data will be analyzed repeatedly, rather than parsing the same files on every query.

In data engineering, XML is usually an interchange format at the edge of a system. Pipelines parse it once, flatten the hierarchy into tables or nested columns, and store the result in a format designed for analytics.

Security risks and common mistakes

XML parsers support features that can be abused by untrusted input, so secure configuration is essential whenever documents come from outside the organization.

ProblemWhat happensRemedy
XML external entity (XXE)Entities read local files or reach internal hostsDisable external entities and DTD processing
Entity expansion attackNested entities expand into gigabytes of textDisable DTDs or enforce expansion limits
Encoding mismatchDeclared encoding differs from actual bytesGenerate UTF-8 consistently and declare it
Unescaped charactersA raw ampersand or angle bracket breaks parsingUse a serializer, never string concatenation
Ignored namespacesXPath queries return no resultsBind namespace prefixes in the query context
Typical XML problems and remedies

A frequent design mistake is the inconsistent choice between attributes and elements. A practical rule is to use attributes for metadata about a value, such as a unit, identifier or language, and child elements for the data itself and anything that may need structure or repetition later.

The simple explanation

XML is a way of writing information so that every piece of data comes with a label. A bare number is not enough. An XML file says that this is the price and that the currency is euros. Labels can sit inside other labels, much like folders inside folders.

The rules are strict. A computer can therefore check whether a file is complete and correct before using it. That reliability is why banks, governments and publishers still rely on XML. Newer formats are shorter, but they are not as easy to check.

How it is used in practice

A mid-sized manufacturer must send electronic invoices to public-sector customers in a country that requires a standardized XML invoice format. Its accounting system exports each invoice as an XML file containing seller and buyer details, line items, tax rates and totals, all in the elements defined by the official schema.

Before sending, an integration service validates every file against the published XSD. In the first week, about one invoice in fifty fails because some product descriptions contain unescaped ampersands and a few tax codes are missing. The team switches the export to a proper XML serializer and adds a required-field check upstream.

After the fix, rejected invoices drop to almost zero, and payment delays caused by format errors disappear. The finance team also uses an XSLT stylesheet to render the same XML files as readable PDF copies for its archive.