Re: Help with XML-SAX program ... it's driving me nuts ...
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: Help with XML-SAX program ... it's driving me nuts ...

From: Fredrik Lundh <fredrik@pythonware.com>
Date: Tue Jan 31 2006 - 13:59:34 CET

mitsura@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>
Received on Tue Feb 7 20:20:12 2006