Python漂亮地打印XML字符串

14

我用Python生成了一个又长又难看的XML字符串,需要通过漂亮打印程序进行过滤以使其更美观。

我找到了这篇帖子介绍了Python的漂亮打印程序,但是我必须将XML字符串写入文件才能读回来使用这些工具,如果可能的话,我想避免这种情况。

有哪些适用于字符串的Python漂亮工具可用?


你使用的是哪个Python XML库? - Paul McMillan
@Paul:我使用“from xml.dom import minidom”。 - prosseek
3个回答

28

以下是将文本字符串解析为lxml结构化数据类型的方法。

Python 2:

from lxml import etree
xml_str = "<parent><child>text</child><child>other text</child></parent>"
root = etree.fromstring(xml_str)
print etree.tostring(root, pretty_print=True)

Python 3:

from lxml import etree
xml_str = "<parent><child>text</child><child>other text</child></parent>"
root = etree.fromstring(xml_str)
print(etree.tostring(root, pretty_print=True).decode())

输出:

<parent>
  <child>text</child>
  <child>other text</child>
</parent>

1
我遇到了一些转义问题,而 etree.tounicode 方法解决了它。 - mut1na
3
在Python 3中,使用print(etree.tostring(tree, pretty_print=True).decode()) - orodbhen

7

我使用lxml库,里面很简单:

>>> print(etree.tostring(root, pretty_print=True))

你可以使用任何 etree 执行该操作,你可以通过程序生成,也可以从文件中读取。
如果你正在使用 PyXML 中的 DOM,则为:
import xml.dom.ext
xml.dom.ext.PrettyPrint(doc)

这会将内容打印到标准输出,除非你指定了其他的流。

http://pyxml.sourceforge.net/topics/howto/node19.html

如果要直接使用minidom,可以使用toprettyxml()函数。

http://docs.python.org/library/xml.dom.minidom.html#xml.dom.minidom.Node.toprettyxml


看起来root和doc都是结构化数据,而不是字符串。感谢您的回答。 - prosseek
如果你的 XML 存在于 minidom 节点中,你可以使用 toprettyxml() 函数。如果它只是一个字符串,那么你需要先解析它才能漂亮地打印出来。 - Paul McMillan

2
这里有一个Python3的解决方案,可以解决难看的换行问题(大量空白),而且它只使用标准库,不像大多数其他实现那样。你提到你已经有一个xml字符串了,所以我假设你使用了xml.dom.minidom.parseString()
使用以下解决方案,您可以避免先写入文件:
import xml.dom.minidom
import os

def pretty_print_xml_given_string(input_string, output_xml):
    """
    Useful for when you are editing xml data on the fly
    """
    xml_string = input_string.toprettyxml()
    xml_string = os.linesep.join([s for s in xml_string.splitlines() if s.strip()]) # remove the weird newline issue
    with open(output_xml, "w") as file_out:
        file_out.write(xml_string)

我找到了如何解决常见的换行问题这里

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接