Unexpected Boolean behavior of Python's xml.etree.ElementTree leaf elements
elementtree, python, xml
Solution
Ok, sorry, after submitting this question I found the explicit statement of the solution in the Python documentation: http://docs.python.org/release/2.6.5/library/xml.etree.elementtree.html#the-element-interface , at the end of the section.
Caution: Because Element objects do not define a nonzero() method, elements with no subelements will test as False.
Sorry for the inconvenience.
Problem
I am experiencing some trouble using the Python 2.6.5 xml.etree.ElementTree library. In particular, if I setup a simple xml element like the following ``` >>> import xml.etree.ElementTree as etree >>> xml = etree.fromstring("<a><b><c>xy</c></b></a>") ``` i have no problems with the library when accessing the inner element nodes, e.g.: ``` >>> etree.tostring(xml.find('b')) '<b><c>xy</c></b>' >>> xml.find('b') == None False >>> bool(xml.find('b')) True ``` However, I am encountering a strange boolean interpretation of leaf element nodes, see: ``` >>> etree.tostring(xml.find('b/c')) '<c>xy</c>' >>> xml.find('b/c') == None False >>> bool(xml.find('b/c')) False ``` Note that in the last command, the element xml.find('b/c'), which is clearly non-None, evaluates to False. This is especially annoying since i cannot use the idiom ``` >>> leaf = xml.find('b/c'): >>> if leaf: >>> do_stuff(leaf) ``` to check whether a leaf element exists. (I have to check explicitly for 'xml.find('b/c') != None'.) Can someone please explain this (for me unexpected) behavior?