"Full" element tag listing possible with Elementtree?
Carl Banks
pavlovevidence at gmail.com
Fri Sep 5 15:19:25 EDT 2008
On Sep 5, 2:27 am, jaime.dy... at gmail.com wrote:
> So, for example, if I had a document that looked like this:
>
> <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.
> Thanks..
Fredrik Lundh wrote Element Tree, so he'd know the best solution, but
I'd like to point out that this is also trivially easy with recursion:
def print_nodes(element, ancestors = []):
s = hierarchy = ancestors + ["<" + element.tag + ">"]
if element.text is not None:
s = s + [element.text]
print " ".join(s)
for subelement in element:
print_nodes(subelement,hierarchy)
Carl Banks
More information about the Python-list
mailing list