Python and XML Help

John Machin sjmachin at
Wed Apr 15 08:09:47 CEST 2009

On Apr 15, 2:25 pm, ookrin <ook... at> wrote:
> Seeing the errors - I changed the two classes to this:
> class offlineLoad():
>     def loadXmlFile(self):
>         print "Loading from File"
>         xf = open('CharacterID.xml','r')
>         xml = xmlHandler()
>         saxparser = make_parser()
>         saxparser.setContentHandler(xml)
>         saxparser.parse(xf)
> class xmlHandler(ContentHandler):
>     def __init__(self):
>         print "---"
>         self.idList = []
>     def startElement(self, name, attrs):
>         if name == "row":
>             charName = attrs.get("name", "")
>             charID = attrs.get("characterID", "")
>             self.buildlist(charName,charID)
>     def buildlist(self,charName,charID):
>         temp = charName,charID
>         self.idList.append(temp)
>         print "----"
>         print self.idList
> I know calling the self.idList = [] in the init probably isn't
> correct, but I couldn't think of any other way currently so it doesn't
> get rebuilt every time the definition gets called. This works and at
> least I think it puts everything into an array for me.

AFAICT having self.idList = [] in the __init__ method is the only
sensible way to do what you want. Non-sensible ways: make it global to
the module, or local to a class method

You do have a problem with what you've got so far: you've done the
heist, you've stuffed the loot into a sack, but where's the getaway
car? IOW your loadXmlFile method needs a line like

   return xml.idList

Wouldn't loadXMLFile be better as a stand-alone function? A class
which is not a subclass of anything more meaty than object and has
only one method (which isn't __init__) smells strongly of excess
reliance on paradigms best left behind with the language from which
you acquired them :-)


More information about the Python-list mailing list