【发布时间】:2015-05-03 01:06:15
【问题描述】:
背景
我正在使用 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")
尝试
我尝试使用tree.write("New_Database.xml", "utf-8") 代替上面的最后一行代码,但它根本没有编辑 XML 的布局 - 它仍然是一团糟。
我还决定摆弄并尝试这样做:tree = minidom.parseString(ET.tostring(root)).toprettyxml(indent = " ")<br> 而不是将其打印到 Python shell,这会给出错误 AttributeError: 'unicode' object has no attribute 'write'.
问题
当我在最后一行将树写入 XML 文件时,有没有办法像打印到 Python shell 一样漂亮地打印到 XML 文件?
我可以在这里使用toprettyxml() 还是有其他方法可以做到这一点?
【问题讨论】:
标签: python xml python-2.6 elementtree pretty-print