7 XPath and XPointer

XPath is a relatively simple language for writing expressions that select a subset of the nodes in a DOM tree. Here are some example XPath expressions, and what nodes they match:

Expression  Meaning 
child::para Selects all children of the context node that are para elements.
child::para[5] Selects the fifth child of the context node that are para elements.
descendant::para Selects all descendants of the context node that are para elements.
ancestor::* Selects all ancestors of the context node

Consult the XPath Recommendation (listed in section 7.1, ``Related Links'') for the full syntax and grammar.

The xml.xpath package contains a parser and evaluator for XPath expressions. The Evaluate(expr, contextNode) function parses an expression and evalates it with respect to the given Element context node. For example:

from xml import xpath

nodes = xpath.Evaluate('quotation/note', doc.documentElement)

If doc is an appropriate DOM tree, then this will return a list containing the subset of nodes denoted by the XPath expression.


Subsections