问题
Is there a way to write XML files in python using the XML library that aren't in one line
I have this code:
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')
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?
回答1:
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
and your output statement to
print(ET.tostring(tree,pretty_print=True),file=open('permission-backup.xml','w'))
This is a Python 3 style print() function call so you need to do
from __future__ import print_function
if you don't already.
来源:https://stackoverflow.com/questions/44004285/python-write-xml-with-spacing