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}
  • Perhaps surprisingly, this query does not find the 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'>
    +
    +
      +
    1. You saw this in the previous example. It finds all the atom:entry elements. +
    2. The find() method takes an ElementTree query and returns the first matching element. +
    3. There are no elements in this entry named 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 to False if they contain no children (i.e. if len(element) is 0). The means that if element.find('...') is not testing whether the find() method found a matching element; it’s testing whether that matching element has any child elements! To test whether the find() method returned an element, use if 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.