Python/XML:漂亮的打印 ElementTree

Python/XML: Pretty-printing ElementTree

我使用 The ElementTree XML API 构造了 XML 并且我希望能够漂亮地打印

我可以使用 ET.write() to write my XML to file and then pretty-print it using many suggestions in Pretty printing XML in Python. However, this requires me to serialize and then deserialize the XML (to disk or to StringIO) 再次漂亮地序列化它 - 这显然不是最理想的。

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

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

file is a file name, or a file object opened for writing.

这包括一个 StringIO 对象。所以:

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

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


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

  • lxml.etree.tostring (answer #2): lxml.etree 是 stdlib etree 的近乎完美的超集,所以如果你打算用它来进行漂亮的打印,只需用它来构建 XML 排在首位。
  • Effbot indent/prettyprint (answer #3):这需要一个 ElementTree 树,这正是您已经拥有的,而不是字符串或文件。

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

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)

Returns XML 格式的结果