我正在使用SQLite访问数据库并检索所需的信息.我在Python 2.6版中使用ElementTree来创建包含该信息的XML文件.
import sqlite3
import xml.etree.ElementTree as ET
# NOTE: Omitted code where I acccess the database,
# pull data, and add elements to the tree
tree = ET.ElementTree(root)
# Pretty printing to Python shell for testing purposes
from xml.dom import minidom
print minidom.parseString(ET.tostring(root)).toprettyxml(indent = " ")
####### Here lies my problem #######
tree.write("New_Database.xml")
Run Code Online (Sandbox Code Playgroud)
我已经尝试使用tree.write("New_Database.xml", "utf-8")上面代码的最后一行,但它根本没有编辑XML的布局 - 它仍然是混乱的混乱.
我还决定摆弄并尝试做:而不是将其打印到Python shell,这给出了错误AttributeError:'unicode'对象没有属性'write'.
tree = minidom.parseString(ET.tostring(root)).toprettyxml(indent = " ")
当我将我的树写到最后一行的XML文件时,是否有一种方法可以像在Python shell中那样打印到XML文件?
我可以toprettyxml()在这里使用,还是有不同的方法来做到这一点?