Python / XML:漂亮的打印ElementTree

问题描述 投票:0回答:2

我使用The ElementTree XML API构建XML,我希望能够漂亮打印

  • 个别节点(用于检查)以及
  • 整个文件(到文件,以备将来检查)。

我可以使用ET.write()将我的XML写入文件,然后使用Pretty printing XML in Python中的许多建议对其进行漂亮打印。但是,这需要我序列化然后反序列化XML(到磁盘或StringIO)只是为了再次将它再次序列化 - 这显然不是最理想的。

那么,有没有办法漂亮打印xml.etree.ElementTree

python xml python-2.7 pretty-print
2个回答
1
投票

正如the docs所说,在write方法:

file是文件名,或者是为写入而打开的文件对象。

这包括StringIO对象。所以:

outfile = cStringIO.StringIO()
tree.write(of)

然后你可以使用你最喜欢的方法漂亮打印outfile - 只需outfile.seek(0)然后将outfile本身传递给一个接收文件的函数,或者将outfile.getvalue()传递给一个带字符串的函数。


但是,请注意,在您链接的问题中打印XML的许多方法甚至都不需要这样。例如:


0
投票

我在使用漂亮的打印时遇到了问题。深入研究我发现以下解决方案对我有用。

import xml.etree.cElementTree as etree
from xml.dom import minidom

root = etree.Element("root")
animal = etree.SubElement(root, "animal")
etree.SubElement(animal, "pet").text = "dog"

xmlstr = 
minidom.parseString(etree.toString(root)).toprettyxml(indent = "   ")
print (xmlstr)

以XML格式返回结果

© www.soinside.com 2019 - 2024. All rights reserved.