简体   繁体   中英

How to get xml output in a file with new line using python xml.etree?

I am generating xml file using "from xml.etree import ElementTree" and placing the generated output in to a new file "test.xml". The output is getting placed inside the test.xml but there is no new line its a big big line. So, what shall i do to have new line inside "test.xml" . Following is the script:

from xml.etree import ElementTree
from xml.dom import minidom
from lxml import etree
def prettify(elem):
    """Return a pretty-printed XML string for the Element.
    """
    rough_string = ElementTree.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="  ")
top = Element('my_document')
comment = Comment('Practising')
top.append(comment)
child = SubElement(top, 'my_information')
childs = SubElement(child,'my_name')
childs.text = 'This child contains text.'
print prettify(top)
file = open("test.xml", 'w')
xml.ElementTree(top).write(file)
file.close()

Why don't you use the return value of the prettify ? Writing the return value of the function will solve your problem.

...
top = Element('my_document')
comment = Comment('Practising')
top.append(comment)
child = SubElement(top, 'my_information')
childs = SubElement(child,'my_name')
childs.text = 'This child contains text.'
with open("test.xml", 'w') as f:  # <--
    f.write(prettify(top))        # <--

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM