如何获得Python的ElementTree精美打印到XML文件? [英] How do I get Python's ElementTree to pretty print to an XML file?

查看:61
本文介绍了如何获得Python的ElementTree精美打印到XML文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用SQLite访问数据库并检索所需的信息。我在Python 2.6版中使用ElementTree来创建包含该信息的XML文件。

I am using SQLite to access a database and retrieve the desired information. I'm using ElementTree in Python version 2.6 to create an XML file with that information.

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的布局-仍然是一团糟。

Attempts

I've tried using tree.write("New_Database.xml", "utf-8") in place of the last line of code above, but it did not edit the XML's layout at all - it's still a jumbled mess.

我还决定四处弄弄并尝试做:

tree = minidom.parseString(ET.tostring(root))。toprettyxml(缩进=)
而不是将其打印到Python shell,这会产生错误 AttributeError:'unicode'对象没有属性'write'

I also decided to fiddle around and tried doing:
tree = minidom.parseString(ET.tostring(root)).toprettyxml(indent = " ")
instead of printing this to the Python shell, which gives the error AttributeError: 'unicode' object has no attribute 'write'.

当我在最后一行将树写入XML文件时,有没有一种方法可以打印出

When I write my tree to an XML file on the last line, is there a way to pretty print to the XML file as it does to the Python shell?

我可以在这里使用 toprettyxml()吗?

Can I use toprettyxml() here or is there a different way to do this?

推荐答案

无论您的XML字符串是什么,您都可以通过以下方式将其写入您选择的文件中:

Whatever your XML string is, you can write it to the file of your choice by opening a file for writing and writing the string to the file.

from xml.dom import minidom

xmlstr = minidom.parseString(ET.tostring(root)).toprettyxml(indent="   ")
with open("New_Database.xml", "w") as f:
    f.write(xmlstr)

有一种可能的复杂性,特别是在Python 2中,它对Unicode的要求不严格,也不那么复杂中的字符字符串。如果您的 toprettyxml 方法交回Unicode字符串( u某物 ),那么您可能需要将其转换为合适的文件编码,例如UTF-8。例如。替换一个写行为:

There is one possible complication, especially in Python 2, which is both less strict and less sophisticated about Unicode characters in strings. If your toprettyxml method hands back a Unicode string (u"something"), then you may want to cast it to a suitable file encoding, such as UTF-8. E.g. replace the one write line with:

f.write(xmlstr.encode('utf-8'))

这篇关于如何获得Python的ElementTree精美打印到XML文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆