Next / Previous / Contents / Shipman's homepage

9.14. Element.iterancestors(): Find an element's ancestors

The ancestors of an element are its parent, its parent's parent, and so on up to the root element of the tree. For any Element instance E, this method returns an iterator that visits E's ancestors in reverse document order:

E.iterancestors(tag=None)

If you omit the argument, the iterator will visit all ancestors. If you wish to visit only ancestors with a specific tag name, pass that tag name as an argument.

Examples:

>>> xml = '''<class sci='Aves' eng='Birds'>
...   <order sci='Strigiformes' eng='Owls'>
...     <family sci='Tytonidae' eng='Barn-Owls'>
...       <genus sci='Tyto'>
...         <species sci='Tyto alba' eng='Barn Owl'/>
...       </genus>
...     </family>
...   </order>
... </class>'''
>>> root = etree.fromstring(xml)
>>> barney = root.xpath('//species') [0]
>>> print "%s: %s" % (barney.get('sci'), barney.get('eng'))
Tyto alba: Barn Owl
>>> for  ancestor in barney.iterancestors():
...     print ancestor.tag,
genus family order class
>>> for  fam in barney.iterancestors('family'):
...    print "%s: %s" % (fam.get('sci'), fam.get('eng'))
Tytonidae: Barn-Owls