XPath (XML Path Language) is a query language for navigating and selecting nodes within an XML document. Defined by the W3C, XPath treats an XML document as a tree of nodes and provides a syntax for traversing that tree using path expressions, similar to how file system paths navigate a directory structure. XPath is a core piece of the XML ecosystem and is used by other W3C specs including XSLT, XQuery, and XML Schema.
XPath expressions can target just about any part of an XML document:
- Path expressions: navigate the node tree using axes like child, parent, ancestor, descendant, and sibling
- Predicates: filter nodes based on conditions in square brackets (e.g., selecting the third item or items with a specific attribute)
- Built-in functions: string manipulation, numeric calculations, boolean logic, and node-set operations
- Wildcards: select nodes regardless of name or type using * and node()
- Abbreviated syntax: shorthand like // for descendant-or-self and @ for attributes
Beyond XML processing, XPath has found a second life in web automation and testing. Tools like Selenium WebDriver use XPath expressions to locate HTML elements on web pages, making it a must-know for QA engineers and test automation developers. XPath can traverse complex DOM structures and select elements based on text content, attributes, or position in the hierarchy, which helps in situations where CSS selectors aren't precise enough.
The current standard is XPath 3.1, but most web testing tools still rely on XPath 1.0 syntax. Knowing the differences between versions saves time when switching between XML processing and browser automation contexts.