Empty lines while using minidom.toprettyxml Empty lines while using minidom.toprettyxml xml xml

Empty lines while using minidom.toprettyxml


I found a solution here: http://code.activestate.com/recipes/576750-pretty-print-xml/

Then I modified it to take a string instead of a file.

from xml.dom.minidom import parseStringpretty_print = lambda data: '\n'.join([line for line in parseString(data).toprettyxml(indent=' '*2).split('\n') if line.strip()])

Output:

<?xml version="1.0" ?><testsuite errors="0" failures="3" name="TestSet_2013-01-23 14_28_00.510935" skip="0" tests="3" time="142.695" timestamp="2013-01-23 14:28:00.515460">  <testcase classname="TC test" name="t1" status="Failed" time="27.013"/>  <testcase classname="TC test" name="t2" status="Failed" time="78.325"/>  <testcase classname="TC test" name="t3" status="Failed" time="37.357"/></testsuite>

This may help you work it into your function a little be easier:

def new_prettify():    reparsed = parseString(CONTENT)    print '\n'.join([line for line in reparsed.toprettyxml(indent=' '*2).split('\n') if line.strip()])


I found an easy solution for this problem, just with changing the last line of your prettify() so it will be:

def prettify(elem):rough_string = xml.tostring(elem, 'utf-8') //xml as ElementTreereparsed = mini.parseString(rough_string) //mini as minidomreturn reparsed.toprettyxml(indent=" ", newl='')


use this to resolve problem with the lines

toprettyxml(indent=' ', newl='\r', encoding="utf-8")