python xml etree,如何使用python xml.etree在新文件中获取xml输出?

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)) #

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值