Expat XML Parser
Carel Fellinger
cfelling at iae.nl
Thu Nov 29 16:46:16 EST 2001
Garth Grimm <garth_grimm at hp.com> wrote:
> I think Martin summed up your answer with the phrase "global variables".
> Haven written primarily python scripts, I ran into the same issue as you a few weeks ago when I
> started doing some XML parsing. I just had to (re)learn scoping issues with Python.
no need to go global, use a class instead, like:
[[not tested and I know nothing about xml]]
class Record:
def __init__(self, **kws):
self.__dict__.update(kws)
class Data:
def __init__(self):
self.data = []
def s_el(self, name, attrs):
self.data.append(Record(type="s_el", name=name, attrs=attrs))
def e_el(self, name):
self.data.append(Record(type="e_el", name=name))
def c_data(self, data):
self.data.append(Record(type="c_el", data=data))
def printit(self):
for r in self.data:
if r.type == "s_el":
print r.name, "(attributes -->", r.attrs, ")"
elif r.type == "e_el":
print " (attribute", r.name, "ends)"
elif r.type == "c_el":
print " `--->", r.data
data = Data()
prs = xml.parsers.expat.ParserCreate()
prs.StartElementHandler = data.s_el
prs.EndElementHandler = data.e_el
prs.CharacterDataHandler = data.c_data
prs.returns_unicode = 0
prs.Parse(xmlpp)
data.printit()
--
groetjes, carel
More information about the Python-list
mailing list