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

2024-04-25 08:46:35 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我找到了this postfor python pretty printers,但是我必须将XML字符串写入一个文件,以便使用这些工具,如果可能的话,我希望避免使用这些工具

有哪些python漂亮的工具可以处理字符串


Tags: 文件工具字符串打印机prettyxmlthisprinters
3条回答

这里有一个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

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

下面介绍如何将文本字符串解析为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>

相关问题 更多 >