Python给定XML字符串,漂亮地打印出XML

问题描述 投票:8回答:3

我用Python生成了一个长而丑陋的XML字符串,我需要通过漂亮的打印机对其进行过滤,以使其看起来更好。

我发现用于python漂亮打印机的this post,但是我必须将XML字符串写到一个文件中才能使用该工具读回,如果可能的话,我想避免。

可用哪些在字符串上可用的python漂亮工具?

python xml pretty-print
3个回答
17
投票

这是从文本字符串解析为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>

6
投票

我使用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

要直接使用minimini,您想使用toprettyxml()功能。

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


0
投票

这是一个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)

我发现了如何解决常见的换行问题here

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