Searching For Nodes Within An XML Document
We'll cover the following...
So far, we’ve worked with this XML document “from the top down,” starting with the root element, getting its child elements, and so on throughout the document. But many uses of XML require you to find specific elements. Etree can do that, too.
import xml.etree.ElementTree as etreetree = etree.parse('feed.xml')root = tree.getroot()print (root.findall('{http://www.w3.org/2005/Atom}entry')) #①#[<Element {http://www.w3.org/2005/Atom}entry at e2b4e0>,# <Element {http://www.w3.org/2005/Atom}entry at e2b510>,# <Element {http://www.w3.org/2005/Atom}entry at e2b540>]print (root.tag)#'{http://www.w3.org/2005/Atom}feed'print (root.findall('{http://www.w3.org/2005/Atom}feed')) #②#[]print (root.findall('{http://www.w3.org/2005/Atom}author')) #③#[]
① The findall()
method finds child elements that match a specific query. (More on the query format in a minute.)
② Each element — including the root element, but also child elements — has a findall()
method. It finds all matching elements among the element’s children. But why aren’t there any results? Although it may not be obvious, this particular query only searches the element’s children. Since the root feed
element has no child named feed
, this query returns an empty list.
③ This result may also surprise you. ...