[Tutor] Elementtree and pretty printing in Python 2.7

Karim karim.liateni at free.fr
Sun Aug 22 17:24:18 CEST 2010


Hello Jerry,

Tricky solution using minidom (standard) Not tested:

import ElementTree
import minidom

def prettyPrint(element):
    txt = ElementTree.tostring(element)
    print minidom.parseString(txt).toprettyxml()


Regards
Karim

On 08/22/2010 04:51 PM, Jerry Hill wrote:
> On Fri, Aug 20, 2010 at 3:49 AM, Knacktus<knacktus at googlemail.com>  wrote:
>    
>> Hi guys,
>>
>> I'm using Python 2.7 and the ElementTree standard-lib to write some xml.
>>
>> My output xml has no line breaks! So, it looks like that:
>>
>> <Items><Project creation_date="heute"/></Items>
>>
>> instead of something like this:
>>
>> <Items>
>>     <Project creation_date="heute"/>
>> </Items>
>>
>> I'm aware of lxml which seems to have a pretty print option, but I would
>> prefer to use the standard-lib ElementTree which seems not to have a feature
>> like this.
>>
>> Do I miss something using the ElementTree-lib or is it bug?
>>      
> Neither, as far as I know.  The XML you get is perfectly valid XML.
> If you want to pretty print it, there's a recipe here:
> http://effbot.org/zone/element-lib.htm#prettyprint, but I don't think
> it's been included in the standard library yet.
>
>    



More information about the Tutor mailing list