Creating xml

Gerhard Häring gh at ghaering.de
Thu Jul 23 17:27:08 EDT 2009


Greg Lindstrom wrote:
> It's been a while since I've played with XML using Python but I've been
> asked to create XML using data from our postgres database.  Currently we
> are generating XML directly from the database using a set of stored
> procedures but it is too slow (yes, I have numbers).  I have been asked
> to create a routine to generate the XML to see if it will be faster that
> the sprocs (which I think it will be, based on other routines we have
> running).  But I digress...

I write to a cStringIO.StringIO instance to create XML. Like this
(pseudo-code):

class Foo:
    def toxml(self, stream):
        print >> stream, "<foo ... />"

If you're concerned about producing valid XML, you can write tests ;-)

> Using my favorite search engine I see that there is a lot of material on
> Python and XML.  At the risk of starting something (which is not my
> intention), what are my options if I want to create xml?  Ceratinly
> writing my own routine is an option, but I bet there are better ones :-)
> 
> How about if I need/want to parse or process an XML file?

Use lxml. It's blazingly fast and its XPath support makes parsing XML a
snap. If you don't want to depend on anything not in the standard
library, use the etree module. Code will be slightly longer because you
don't have XPath support and performance will be only "ok". Not
"super-fast", like with lxml.

HTH

-- Gerhard




More information about the Python-list mailing list