[Tutor] No Elegant XML Output in ElementTree?

Marc Tompkins marc.tompkins at gmail.com
Tue Jul 28 07:55:44 CEST 2009


On Mon, Jul 27, 2009 at 8:32 PM, Luis Galvan <cynicalairrick at gmail.com>wrote:

> Hi tutors,
> Okay, so I just started to learn ElementTree (and XML processing in
> general) and I just can't, for the life of me, find a way to output the XML
> file in an actual hierarchic presentation.


What you want is generically called "prettyprinting".  I don't use
ElementTree myself (I use Amara/Akara), so I don't know whether effbot
followed through on this, but take a look at this page:
http://effbot.org/zone/element-lib.htm

I also found this page:
http://renesd.blogspot.com/2007/05/pretty-print-xml-with-python.html
and in the comments there's this, which looks pretty simple:

To pretty print an ElementTree:

from xml.minidom import parseString
from xml.etree import ElementTree

def prettyPrint(element):
    txt = ElementTree.tostring(element)
    print minidom.parseString(txt).toprettyxml()
Substitute output to a file for "print", and you're done.In Amara, I do
this:
    def Save(self):
        outFile = open(self.fileName,'w+b')
        self.xDoc.xml(outFile,indent=u'yes')
        outFile.close()
but that's not much help for etree, I know...

-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090727/a6024b3d/attachment.htm>


More information about the Tutor mailing list