python用空格写xml [英] python write xml with spacing
本文介绍了python用空格写xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法使用不在一行中的 XML 库在 python 中编写 XML 文件
Is there a way to write XML files in python using the XML library that aren't in one line
我有这个代码:
import xml.etree.ElementTree as ET
perm = ET.Element('perm')
connect = ET.SubElement(perm, 'connect').text="*"
download = ET.SubElement(perm, 'download').text="*"
upload = ET.SubElement(perm, 'upload').text="*"
view = ET.SubElement(perm, 'view').text="*"
delFile = ET.SubElement(perm, 'delete_file').text="*"
delDir = ET.SubElement(perm, 'delete_dir').text="*"
rename = ET.SubElement(perm, 'rename').text="*"
create_dir = ET.SubElement(perm, 'create_dir').text="*"
sizeof = ET.SubElement(perm, 'sizeof').text="*"
tree = ET.ElementTree(perm)
tree.write('permission-backup.xml')
但是 xml 看起来像这样:
but the xml looks like this:
<perm><connect>*</connect><download>*</download><upload>*</upload><view>*</view><delete_file>*</delete_file><delete_dir>*</delete_dir><rename>*</rename><create_dir>*</create_dir><sizeof>*</sizeof></perm>
有没有办法让它在不打开文件并重新格式化的情况下写入多行而不是一行?
is there any way to make it write multiple lines instead of one without opening the file and re-formatting it?
推荐答案
解决此问题的一种方法是使用 lxml
而不是 xml
.它是一种替代品,因此您只需要将 import
语句更改为
One way to fix this is to use lxml
instead of xml
. It is a drop-in replacement so you only have to change your import
statement to
from lxml import etree as ET
和你的输出语句
print(ET.tostring(tree,pretty_print=True),file=open('permission-backup.xml','w'))
这是一个 Python 3 风格的 print()
函数调用,所以你需要做
This is a Python 3 style print()
function call so you need to do
from __future__ import print_function
如果你还没有.
这篇关于python用空格写xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文