在python中通过xml.etree.ElementTree生成的xml文件中插入换行符 [英] inserting newlines in xml file generated via xml.etree.ElementTree in python
问题描述
我在 python 中使用 xml.etree.ElementTree 创建了一个 xml 文件.然后我使用
I have created a xml file using xml.etree.ElementTree in python. I then use
tree.write(filename, "UTF-8")
将文档写到文件中.
但是当我使用文本编辑器打开文件名时,标签之间没有换行符.一切都是一条大线
But when I open filename using a text editor, there are no newlines between the tags. Everything is one big line
我怎样才能以漂亮的印刷"格式写出文档?格式,以便在所有 xml 标签之间有新行(希望有缩进等)?
How can I write out the document in a "pretty printed" format so that there are new lines (and hopefully indentations etc) between all the xml tags?
推荐答案
我认为最简单的解决方案是切换到 lxml 图书馆.在大多数情况下,您只需将导入从 import xml.etree.ElementTree as etree
更改为 from lxml import etree
或类似.
The easiest solution I think is switching to the lxml library. In most circumstances you can just change your import from import xml.etree.ElementTree as etree
to from lxml import etree
or similar.
然后您可以在序列化时使用 pretty_print
选项:
You can then use the pretty_print
option when serializing:
tree.write(filename, pretty_print=True)
(也可在 etree.tostring
上找到)
这篇关于在python中通过xml.etree.ElementTree生成的xml文件中插入换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!