有没有办法使用不在一行中的XML库在python中编写XML文件
我有这段代码:
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看起来像这样:
<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>
有没有办法让它写一行而不是一行而不打开文件并重新格式化?
答案 0 :(得分:0)
解决此问题的一种方法是使用lxml
代替xml
。这是替代品,因此您只需将import
声明更改为
from lxml import etree as ET
和你的输出语句
print(ET.tostring(tree,pretty_print=True),file=open('permission-backup.xml','w'))
这是一个Python 3样式print()
函数调用,所以你需要做
from __future__ import print_function
如果你还没有。