Back to Blog
Technicalxmlxpathdata

XML and XPath: Understanding Structured Data and Powerful Queries

XML fundamentals and the XPath query language: namespaces, well-formedness, axes and predicates, and when XML is a better fit than JSON.

LoopalooPublished January 9, 202612 min read

Few technologies in the history of computing have been as simultaneously ubiquitous and misunderstood as XML. It holds the configuration of countless applications, underpins document formats like DOCX and SVG, carries news and podcast feeds, and forms the backbone of enterprise integration systems in industries from healthcare to finance. Yet many developers meet XML only as an annoyance, something verbose they wish were JSON instead. This guide covers what XML actually is, why it was designed the way it was, and how to query it with XPath, which together turn it from an inconvenience into a precise tool for structured data.

A Brief History of XML

XML, the Extensible Markup Language, did not emerge in a vacuum. Its lineage traces back to SGML, the Standard Generalized Markup Language, which was standardized as ISO 8879 in 1986. SGML was a meta-language for defining document markup languages, and it was extraordinarily powerful but also extraordinarily complex. HTML itself was originally defined as an SGML application. By the mid-1990s, the web was exploding in popularity, and there was a clear need for a data format that carried SGML's strengths (extensibility, self-description, and strict structure) without its daunting complexity.

The World Wide Web Consortium convened a working group that produced the XML 1.0 specification, published as a W3C Recommendation in February 1998. The design goals were explicit and deliberate: XML should be straightforwardly usable over the Internet, it should support a wide variety of applications, it should be compatible with SGML, it should be easy to write programs that process XML documents, and the design should be formal and concise. These goals shaped a language that struck a balance between human readability and machine parseability, and that balance is precisely why XML has endured for more than a quarter century even as fashions in data formats have shifted.

XML's Design Philosophy

At its core, XML is a set of rules for encoding documents and data in a format that is both human-readable and machine-readable. Unlike binary formats, which require specific software to interpret, an XML file can be opened in any text editor and understood by a person with no special tools. The tags describe the data they contain, making XML self-documenting in a way that comma-separated values or fixed-width formats never are.

XML's strictness is deliberate. While HTML browsers are famously forgiving of malformed markup (unclosed tags, mismatched nesting, missing quotes), XML parsers are required to reject any document that violates the syntax rules. This strictness eliminates an entire class of ambiguity that plagues loosely parsed formats. When an XML document parses successfully, you know with certainty that every tag is properly opened and closed, every attribute value is quoted, and the document structure forms a valid tree. This predictability matters most in automated systems, where ambiguity can propagate into subtle, hard-to-diagnose bugs. The Loopaloo XML Formatter & Tools checks and pretty-prints XML documents and reports errors with the line where they occur, so you can spot structural issues before they cause problems downstream.

Syntax Rules: Well-Formedness and Validity

XML imposes two distinct levels of correctness. The first, well-formedness, is non-negotiable. A well-formed XML document must have exactly one root element, every opening tag must have a corresponding closing tag (or use the self-closing syntax), elements must be properly nested without overlapping, attribute values must be enclosed in quotes, and certain characters like angle brackets and ampersands must be escaped using entity references. These rules are absolute: a document that violates any of them is not XML, and a conforming parser must refuse to process it.

The second level, validity, is optional but powerful. A valid XML document is not only well-formed but also conforms to a schema that defines the allowed elements, attributes, their data types, and the structure in which they may appear. The two most common schema languages are DTD (Document Type Definition), which dates from the SGML era and uses a compact but limited syntax, and XML Schema (often called XSD), which is itself written in XML and offers rich data typing, namespace support, and fine-grained structural constraints. Validity checking earns its keep in data exchange scenarios where you need to ensure that incoming documents conform to an agreed-upon structure before processing them.

Namespaces and Why They Matter

One of XML's most important and most frequently confusing features is namespaces. The problem they solve is straightforward: when you combine XML documents from different sources, element names can collide. A <title> element in a book catalog means something entirely different from a <title> element in an SVG drawing or an HTML page. Without namespaces, a parser processing a composite document would have no way to distinguish between these identically named but semantically unrelated elements.

XML namespaces solve this by associating each element and attribute with a URI, typically declared via the xmlns attribute. The URI does not need to point to an actual web resource; it simply serves as a globally unique identifier. In practice, namespaces allow documents from different vocabularies (XHTML, SVG, MathML, custom business schemas) to coexist within a single document without ambiguity. The syntax can be verbose, which contributes to XML's reputation for wordiness, but the mechanism itself is elegant, and large-scale data integration depends on it.

XML vs. JSON: When Each Is Appropriate

The most common contemporary critique of XML is that JSON is simpler, lighter, and better suited to modern web development. This is often true for API responses and frontend data exchange, where JSON's native compatibility with JavaScript and its minimal syntax make it the more practical choice. For that side of the work, the JSON Formatter & Validator gives JSON the same kind of structural clarity that the XML Formatter & Tools gives XML.

However, the assertion that JSON should replace XML everywhere misunderstands the strengths of each format. XML excels in scenarios that JSON handles poorly or not at all. Document markup, where you need to mix text with structural annotations, is XML's original domain and one where JSON is awkward at best. Schema validation, where you need a rigorous mechanism for defining and enforcing document structure, has W3C-standardized schema languages in XML; JSON Schema fills that role for JSON and is widely used, but it isn't published by a standards body like the W3C or IETF. Namespaces, which let you compose documents from multiple vocabularies, have no equivalent in JSON. XSLT transformations, which convert XML documents between formats using declarative rules, have no standardized JSON equivalent.

In practice, XML remains the dominant format for SOAP-based web services, enterprise integration platforms, configuration files for applications like Maven, Spring, and Android, document formats like Office Open XML and SVG, syndication feeds like RSS and Atom, and industries with deeply entrenched XML standards such as HL7 in healthcare and XBRL in financial reporting. Neither format is objectively better. The right choice is the one that matches the requirements.

XPath: A Query Language for XML

If XML is a way of structuring data, XPath is the language for reaching into that structure and extracting exactly what you need. Published as a W3C Recommendation alongside XSLT in 1999, XPath provides a syntax for navigating an XML document's tree structure and selecting specific nodes. The analogy to file system paths is instructive: just as /home/user/documents/report.pdf navigates a directory hierarchy to locate a specific file, an XPath expression like /catalog/book/title navigates an XML document hierarchy to locate specific elements.

But XPath is far more expressive than file system paths. It supports wildcards, predicates, functions, and multiple axes of navigation that make it possible to express complex queries concisely. The Loopaloo XPath Tester lets you run XPath expressions against your own XML and see the results immediately, which makes it a handy way to learn the language and debug queries.

XPath Axes: Navigating the Document Tree

An XPath axis defines a direction of navigation relative to the current node. The most commonly used axis is child, which selects the direct children of the current node and is the default when you write a simple path like /catalog/book. The descendant axis selects all nodes below the current node at any depth, which is essentially what the double-slash shorthand // does (strictly, // is short for /descendant-or-self::node()/). Writing //title selects every title element anywhere in the document, regardless of how deeply it is nested.

The parent axis moves upward in the tree, selecting the parent of the current node. The ancestor axis extends this to select all nodes above the current node up to and including the root. The sibling axes (preceding-sibling and following-sibling) select nodes that share the same parent and appear before or after the current node in document order. The preceding and following axes are broader, selecting nodes that appear before or after the current node anywhere in the document, apart from its own ancestors and descendants.

These axes give XPath a navigational flexibility that few query languages can match. You can start at any node in the document, travel in any direction along the tree, filter the results, and arrive at precisely the set of nodes you need.

XPath Predicates and Functions

Predicates are the mechanism by which XPath filters node sets. Enclosed in square brackets, a predicate narrows a selection to only those nodes that satisfy a condition. The expression /catalog/book[price > 30] selects all book elements whose price child contains a value greater than 30. The expression /catalog/book[1] selects only the first book element, using the position() function implicitly.

XPath provides a library of built-in functions for working with strings, numbers, and node sets. The contains() function tests whether a string contains a given substring, making expressions like //book[contains(title, 'XML')] possible. The string-length() function returns the number of characters in a string, useful for validation queries. The count() function returns the number of nodes in a node set, sum() adds numeric values, and normalize-space() strips leading and trailing whitespace and collapses internal whitespace sequences. Together, predicates and functions turn XPath from a simple navigation language into a real query language capable of expressing sophisticated retrieval logic.

Practical XPath Examples

Consider an XML document representing a bookstore catalog with nested book elements, each containing title, author, price, and category children. To select all book titles, you would write /bookstore/book/title. To find books cheaper than twenty dollars, the expression becomes /bookstore/book[price < 20]. To find books in the "programming" category by a specific author, you could write /bookstore/book[category='programming' and author='Kernighan']. To count the total number of books, you would use count(/bookstore/book). Each of these expressions can be tested and refined interactively in the XPath Tester, which shows the matching nodes (or the number, string, or true/false value an expression returns) next to the XML you're querying, so you can confirm that your query captures exactly what you intend.

XSLT and How XPath Powers Transformations

XSLT, the Extensible Stylesheet Language Transformations, is a language for transforming XML documents into other formats: different XML structures, HTML, plain text, or virtually any text-based output. XSLT templates use XPath expressions to match and select nodes from the source document, then define the output to produce for each matched node. Without XPath, XSLT would have no way to identify which parts of the source document to transform. In this sense, XPath is the addressing mechanism and XSLT is the transformation engine; together, they form a powerful declarative programming model for document processing.

While XSLT's popularity has waned in the age of JavaScript-driven frontends, it remains actively used in publishing workflows, enterprise data transformations, and any context where XML-to-XML or XML-to-HTML conversion is needed. The declarative nature of XSLT makes certain transformations (restructuring deeply nested documents, aggregating data across sibling elements, conditionally including content) far more concise than equivalent imperative code.

XPath in Modern Contexts

Despite XML's reputation as a legacy technology, XPath continues to find new applications in modern development. Web scraping tools and libraries, including Python's lxml and JavaScript's various DOM parsers, support XPath as a first-class mechanism for extracting content from HTML documents. While CSS selectors are often preferred for simple selections, XPath's ability to navigate upward in the tree, filter by text content, and combine complex predicates makes it indispensable for non-trivial extraction tasks.

In automated testing, Selenium WebDriver supports XPath for locating elements on web pages, and many test suites use it heavily. An expression like //label[normalize-space()='Email']/following-sibling::input finds an input by the text of its label and then moves sideways in the tree, two things CSS selectors can't express. Command-line tools such as xmlstarlet use XPath to read and change settings in XML configuration files, and because SVG is pure XML, the same queries work for selecting and editing graphical elements.

XPath 2.0 and 3.0: Evolution of the Language

The original XPath 1.0 specification, capable as it was, had clear limitations. It supported only four data types (node sets, strings, numbers, and booleans), and its function library was modest. XPath 2.0, published in 2007 as part of the XQuery and XSLT 2.0 family, dramatically expanded the language. It introduced a rich type system based on XML Schema data types, support for sequences (ordered lists of items), conditional expressions with if/then/else, quantified expressions with some and every, and a vastly expanded function library including regular expression support, date and time functions, and aggregate functions.

XPath 3.0 and 3.1 pushed further, adding higher-order functions (the ability to pass functions as arguments to other functions), the let expression for variable bindings, string concatenation operators, and support for maps and arrays that makes XPath capable of processing JSON as well as XML. These later versions turn XPath from a simple path language into a full functional programming language. Support is another matter: browsers still implement only XPath 1.0, and many other tools stop there too.

The RSS, Atom, and XHTML Legacy

Some of the most enduring applications of XML are formats that people use every day without realizing they are interacting with XML at all. RSS (Really Simple Syndication) and Atom are XML-based formats that power the feeds behind podcasts, news aggregators, and blog subscriptions. Every podcast app learns about new episodes from an RSS feed, and every post in your feed reader arrived as part of an XML document. XHTML, the reformulation of HTML as valid XML, enforced the strict parsing rules of XML on web documents and, while it eventually lost the standards battle to HTML5's more forgiving parser, its influence shaped a generation of web developers' understanding of well-formed markup.

These formats demonstrate XML's enduring strength as an interchange format: they are human-readable, widely supported by tooling, rigorously defined by public specifications, and immune to the ambiguity that undermines loosely structured alternatives. For parsing feeds, validating configuration files, or pulling data out of complex documents, XML and XPath are still the right tools. The XML Formatter & Tools and XPath Tester bring them into your browser, so you can format, validate, and query XML documents without installing specialized software or writing boilerplate code.

Related Tools

Related Articles