CHAPTER 12 ■ XML
199
>>> tree = lxml.etree.parse('examples/feed.xml')
>>> NSMAP = {'atom': 'http://www.w3.org/2005/Atom'} (1)
>>> entries = tree.xpath("//atom:category[@term='accessibility']/..", (2)
... namespaces=NSMAP)
>>> entries (3)
[<Element {http://www.w3.org/2005/Atom}entry at e2b630>]
>>> entry = entries[0]
>>> entry.xpath('./atom:title/text()', namespaces=NSMAP) (4)
['Accessibility is a harsh mistress']
1. To perform XPath queries on namespaced elements, you need to define a
namespace prefix mapping. This is just a Python dictionary.
2. Here is an XPath query. The XPath expression searches for category elements
(in the Atom namespace) that contain a term attribute with the value
accessibility. But that’s not actually the query ...