[issue21028] ElementTree objects should support all the same methods as Element objects

Stefan Behnel report at bugs.python.org
Sun Mar 23 08:34:21 CET 2014


Stefan Behnel added the comment:

catalog = xml.etree.ElementTree.parse('books.xml')

    # This succeeds
    for book in catalog.findall('book'):
        print(book.tag)

This is a bit of a convenience break in the API. The "normal" way to do it would be either catalog.getroot().findall('book') or catalog.findall('/catalog/book'). There is not much use in requiring to include the root element in the path expression, therefore it's allowed to leave it out. Note that you can't use absolute path expressions on Elements, this is a difference to the ElementTree object.


    # This fails:
    for book in catalog:
        print(book.tag)

Iterating over an ElementTree? What would that even mean? Why would you expect it to iterate over the children of the root Element, and not, say, all Elements in the document? I think that ambiguity is a good reason to not make ElementTree objects iterable.


    # But for inner elements, we have more options
    book = catalog.find('bk101')
    for subelement in book:
        print(subelement.tag)


> Note, the XML data model requires that the outermost element have some capabilities that inner elements don't have (such as comments and processing instructions).  That said, the outer element shouldn't have fewer capabilities that the inner elements.

ISTM that you are misinterpreting the ElementTree object as representing the document root whereas it actually represents the document. The root Element is given by tree.getroot().

----------
nosy: +eli.bendersky, scoder

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue21028>
_______________________________________


More information about the Python-bugs-list mailing list