XPath

XPath is a recommendation of the World Wide Web Consortium (W3C) for locating nodes in an XML document tree. XPath is not designed to be used alone but in conjunction with other tools, such as XSLT or XPointer. These tools use XPath intensively and extend it for their own needs through new functions and new basic types.

XPath provides a syntax for locating a node in an XML document. It takes its inspiration from the syntax used to denote paths in filesystems such as Unix. This node, often called the context node, depends on the context of the XPath expression. For example, the context of an XSLT expression found in an <xsl:template match="para"> template will be the selected <para> element (recall that XSLT templates use XPath expressions). This node can be compared to a Unix shell’s current directory.

Given our earlier XML examples, it is possible to write the following expressions:

chapter

Selects the <chapter> element descendants of the context node

chapter/para

Selects the <para> element descendants of the <chapter> element children of the context node

../chapter

Selects the <chapter> element descendants of the parent of the context node

./chapter

Selects the <chapter> element descendants of the context node

*

Selects all element children of the context node

*/para

Selects the <para> grandchildren of the context node

.//para

Selects the <para> element descendants (children, children of children, etc.) of the context node

/para

Selects the <para> element children ...

Get Webmaster in a Nutshell, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.