diff --git a/xml.html b/xml.html index 218dc93..b1104eb 100755 --- a/xml.html +++ b/xml.html @@ -365,6 +365,30 @@ mark{display:inline}
author elements in this document. Why not? Because this is just a shortcut for tree.getroot().findall('{http://www.w3.org/2005/Atom}author'), which means “find all the author elements that are children of the root element.” The author elements are not children of the root element; they’re children of the entry elements. Thus the query doesn’t return any matches.
+There is also a find() method which returns the first matching element. This is useful for situations where you are only expecting one match, or if there are multiple matches, you only care about the first one.
+
+
+>>> entries = tree.findall('{http://www.w3.org/2005/Atom}entry') ① +>>> len(entries) +3 +>>> title_element = entries[0].find('{http://www.w3.org/2005/Atom}title') ② +>>> title_element.text +'Dive into history, 2009 edition' +>>> foo_element = entries[0].find('{http://www.w3.org/2005/Atom}foo') ③ +>>> foo_element +>>> type(foo_element) +<class 'NoneType'> ++
atom:entry elements.
+find() method takes an ElementTree query and returns the first matching element.
+foo, so this returns None.
+++☞There is a “gotcha” with the
find()method that will eventually bite you. In a boolean context, ElementTree element objects will evaluate toFalseif they contain no children (i.e. iflen(element)is0). The means thatif element.find('...')is not testing whether thefind()method found a matching element; it’s testing whether that matching element has any child elements! To test whether thefind()method returned an element, useif element.find('...') is not None. +
There is a way to search for descendant elements, i.e. children, grandchildren, and any element at any nesting level.