"Full" element tag listing possible with Elementtree?

jaime.dyson at gmail.com jaime.dyson at gmail.com
Fri Sep 5 20:11:13 CEST 2008


On Sep 4, 11:43 pm, Fredrik Lundh <fred... at pythonware.com> wrote:
> jaime.dy... 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>

Fantastic.  Thank you very much, Fredrik!  And thanks for ET!



More information about the Python-list mailing list