python用间距写xml

时间:2017-05-16 14:27:35

标签: python-2.7 xml-parsing

有没有办法使用不在一行中的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>

有没有办法让它写一行而不是一行而不打开文件并重新格式化?

1 个答案:

答案 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

如果你还没有。