문제

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?

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top