constructin trees in python

Maxim Mercury maxim.mercury at gmail.com
Sat Nov 20 09:28:08 CET 2010


Hi ,
Iam very much new to python. Iam trying to construct a xml dom tree
using the builtin HTMLParser class (on data event callbacks). Iam
maintaining the childs as a list of elements and whenver the sax
parser encounters a tag i push it to a local stack, my basic logic is
below.

**************
def handle_starttag(self, tag, attrs):
curElement=HTMLElement(tag.lower(),
attrs);                                        <------ (1)

if(self.elementRoot == None):
     self.elementRoot = curElement
else:
 
self.elementStack[-1].childs.append(curElement)
<------ (2)

self.elementStack.append(curElement)

**************

here is the definintion of htmlelement

class HTMLElement:
    tag=None
    attrs={}
    data=''
    childs=[]

the issue is the though new elements are pushed in the stack (1),
whenever i append the child to the stack top all other elements in the
stack is getting affected, i assume the same reference is used but is
there a way to overcome this ?



More information about the Python-list mailing list