[英]How to get xml output in a file with new line using python xml.etree?
我正在使用“從xml.etree import ElementTree”生成xml文件,並將生成的輸出放入新文件“ test.xml”中。 輸出將放置在test.xml內,但是沒有新行是很大的一行。 因此,我應該怎么做才能在“ test.xml”中插入新行。 以下是腳本:
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()
您為什么不使用prettify
的返回值? 編寫函數的返回值將解決您的問題。
...
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)) # <--
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.