python write xml with spacing

旧时模样 提交于 2019-12-25 10:55:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!