Python and XML Help

John Machin sjmachin at lexicon.net
Tue Apr 14 23:15:04 EDT 2009


On Apr 15, 12:29 pm, ookrin <ook... at gmail.com> wrote:
> On Apr 12, 12:51 am, "Diez B. Roggisch" <de... at nospam.web.de> wrote:
>
>
>
> > ookrin schrieb:
>
> > > I'm in the process of learning python and PyQt4. I had decided to make
> > > myself a simple app and soon discovered that I needed to crash into
> > > xml to use some of the data I was going to be getting off of the
> > > server.
>
> > > I picked up enough xml to use the sax parser to get the data out of
> > > the xml. I can get as far as printing it to the screen, but there is
> > > where I get stuck.... I can't seem to send the data to anywhere else,
> > > into another variable, to another function. The parser stops after the
> > > first line it finds.
>
> > > class offlineLoad():
> > >     def loadXmlFile(self):
> > >         print "Loading from File"
> > >         xf = open('CharacterID.xml','r')
> > >         xml = xmlHandler()
> > >         saxparser = make_parser()
> > >         print "parser created"
> > >         saxparser.setContentHandler(xml)
> > >         print "parser runn"
> > >         try:
> > >             saxparser.parse(xf)
> > >         except:
> > >             print "Error Reading xml"
>
> > This is a very bad thing to do - there are only very few justified cases
> > of catch-all for exceptions. This certainly isn't one, as it suppresses
> > the real cause for what is happening.
>
> > Which makes it harder for you & for us to diagnose the problem, because
> > you don't show (and currently can't) the stacktrace to us.
>
> > Please show us the stacktrace you suppress. Then help might be possible.
>
> There is actually no stacktrace
> error. It will just print me the error message that I have when I try
> to send the variables outside of the if loop. (from the try - except
> statement.)

That's because (as Diez has already pointed out, and told you to stop
doing) you are *suppressing* the error message and stack trace that
will help diagnose what is going wrong in your callback method.

Instead of this:
        try:
            saxparser.parse(xf)
        except:
            print "Error Reading xml"
do just this:
        saxparser.parse(xf)
or if you really want to print something at the time, do this:
        try:
            saxparser.parse(xf)
        except:
            print "something meaningful"
            raise # throw the exception back for normal handling

And just in case you're not taking the advice of Scott D. D. either,
let me tell you again: use ElementTree, it's easier (no callbacks to
complicate things) and the ratio of helpful-user-count to problem-
likelihood is likely to be much higher than with sax.

Cheers,
John



More information about the Python-list mailing list