如何使用python xml.etree在新文件中获取xml输出? [英] How to get xml output in a file with new line using python xml.etree?

查看:673
本文介绍了如何使用python xml.etree在新文件中获取xml输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用from xml.etree import ElementTree生成xml文件,并将生成的输出放置到一个新文件test.xml中。输出被放置在test.xml中,但没有新的行,它是一个很大的线。那么,我应该做些什么来在test.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()


推荐答案

你不使用 prettify 的返回值吗?编写函数的返回值将解决您的问题。

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

这篇关于如何使用python xml.etree在新文件中获取xml输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆