Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with newlines when I use toprettyxml()

Tags:

python

xml

I'm currently using the toprettyxml() function of the xml.dom module in a Python script and I'm having some trouble with the newlines. If don't use the newl parameter or if I use toprettyxml(newl='\n') it displays several newlines instead of only one.

For instance

f = open(filename, 'w')
f.write(dom1.toprettyxml(encoding='UTF-8'))
f.close()

displayed:

<params>


    <param name="Level" value="#LEVEL#"/>


    <param name="Code" value="281"/>


</params>

Does anyone know where the problem comes from and how I can use it? FYI I'm using Python 2.6.1

like image 306
pierroz Avatar asked Nov 02 '09 16:11

pierroz


1 Answers

I found another great solution :

f = open(filename, 'w')
dom_string = dom1.toprettyxml(encoding='UTF-8')
dom_string = os.linesep.join([s for s in dom_string.splitlines() if s.strip()])
f.write(dom_string)
f.close()

Above solution basically removes the unwanted newlines from the dom_string which are generated by toprettyxml().

Inputs taken from -> What's a quick one-liner to remove empty lines from a python string?

like image 91
dganesh2002 Avatar answered Nov 16 '22 03:11

dganesh2002