How to generate XML

Andrew Dalke dalke at dalkescientific.com
Thu Dec 20 13:05:22 EST 2001


Fabrizio:
> Does anybody know if there are modules to generate XML?
> I know there is SAX, but it is only for parsing, isn't it?

Others have mentioned DOM.  You can also use SAX to
generate XML, if you're careful.

from xml.sax import saxutils
gen = saxutils.XMLGenerator()

gen.startDocument()
gen.startElement("begin", {})
gen.characters("some <text> that gets &escaped;\n")
gen.endElement("begin")
gen.endDocument()

prints the following

<?xml version="1.0" encoding="iso-8859-1"?>
<begin>some <text> that gets &escaped;
</begin>

I've written a few tree traveral algorithms which
mimic the SAX event mechanism.  Makes it very easy
to convert the tree to XML.

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list