"Full" element tag listing possible with Elementtree?

Fredrik Lundh fredrik at pythonware.com
Fri Sep 5 08:43:15 CEST 2008


jaime.dyson at gmail.com wrote:

> <a>
>   <b att="atttag" content="b"> this is node b </b>
>   <c> this is node c
>     <d />
>     <e> this is node e </e>
>   </c>
>   <f> this is node f </f>
> </a>
> 
> I would want to print the following:
> 
> <a>
> <a> <b>
> <a> <b> text: this is node b
> <a> <c>
> <a> <c> text: this is node c
> <a> <c> <d>
> <a> <c> <e>
> <a> <c> <e> text: this is node e
> <a> <f>
> <a> <f> this is node f
> 
> Is there a simple way to do this?  Any help would be appreciated.

in stock ET, using a parent map is probably the easiest way to do this:

     http://effbot.org/zone/element.htm#accessing-parents

that is, for a given ET structure "tree", you can do

parent_map = dict((c, p) for p in tree.getiterator() for c in p)

def get_parents(elem):
     parents = []
     while 1:
         elem = parent_map.get(elem)
         if elem is None:
             break
         parents.append(elem)
     return reversed(parents)

for elem in tree.getiterator():
     print list(get_parents(elem)), elem

</F>




More information about the Python-list mailing list