0

Code

I'm writing an xml file with cElementTree like this:

cElementTree.ElementTree(xml_tree]).write(xmlPath, encoding="ISO-8859-1", xml_declaration=True)  

actual result

This gives the following file (on Windows):

<?xml version='1.0' encoding='iso-8859-1'?><tag1 = "1"></tag1>

So the newlines are missing.

I tried adding the appropiate windows newline characters \r\n 'by hand', now I get this:

<?xml version='1.0' encoding='iso-8859-1'?><tag1 = "1">
</tag1>

desired result

However, I would like to have the correct newline character after each line, so that my output should look this:

<?xml version='1.0' encoding='iso-8859-1'?>
<tag1 = "1">
</tag1>

How can I achieve that?

user1251007
  • 15,891
  • 14
  • 50
  • 76
  • The newlines have no meaning. –  Oct 19 '12 at 13:30
  • 1
    Besides the link in @Tichodroma's answer, there is also [this one](http://stackoverflow.com/questions/749796/pretty-printing-xml-in-python), which has even more (and possibly better) information. – John Y Oct 19 '12 at 13:51
  • @Tichodroma: I know that, though I have a tool that cannot read the xml file without newlines. And I cannot change this tool :-( – user1251007 Oct 19 '12 at 14:31

1 Answers1

2

lxml supports pretty printing, cElementTree doesn't.

from lxml import etree
xml_str = "<parent><child>text</child><child>other text</child></parent>"
root = etree.fromstring(xml_str)
print etree.tostring(root, pretty_print=True)

See Python pretty XML printer for XML string and Pretty printing XML in Python

Community
  • 1
  • 1
  • Thanks for your answer! But lxml is not included in the standard installation of python. As I want to use this on several computers, this is a "no go", unfortunately. – user1251007 Oct 19 '12 at 14:54