Help with XML-SAX program ... it's driving me nuts ...
Fredrik Lundh
fredrik at pythonware.com
Tue Jan 31 07:59:34 EST 2006
mitsura at skynet.be wrote:
> I need to read a simle XML file. For this I use the SAX parser. So far
> so good. The XML file consist out of number of "Service" object with
> each object a set of attributes.
> The strange thing is that for some reason, the attributes for all the
> objects are being updated. I don't understand why this happens.
you're using the same dictionary for all Service elements:
obj.attributes = self.attribs
adds a reference to the attribs dictionary; it doesn't make a copy (if it
did, your code wouldn't work anyway).
changing
self.attribs.clear()
to
self.attribs = {} # use a new dict for the next round
fixes this.
> It's driving me nuts. I have spend hours going through this very simple
> code, but I can't find what's wrong.
simple? fwiw, here's the corresponding ElementTree solution:
import elementtree.ElementTree as ET
for event, elem in ET.iterparse("kd.xml"):
if elem.tag == "Service":
d = {}
for e in elem.findall("Attribute"):
d[e.findtext("Name")] = e.findtext("Value")
print elem.findtext("Name"), d
(tweak as necessary)
</F>
More information about the Python-list
mailing list