我用 Python 生成了一个又长又丑的 XML 字符串,我需要通过漂亮的打印机对其进行过滤以使其看起来更好。
我为 python 漂亮的打印机找到了这篇文章,但我必须将 XML 字符串写入一个文件以读取回以使用这些工具,如果可能的话,我想避免这种情况。
有哪些可用于字符串的 Python 漂亮工具?
我用 Python 生成了一个又长又丑的 XML 字符串,我需要通过漂亮的打印机对其进行过滤以使其看起来更好。
我为 python 漂亮的打印机找到了这篇文章,但我必须将 XML 字符串写入一个文件以读取回以使用这些工具,如果可能的话,我想避免这种情况。
有哪些可用于字符串的 Python 漂亮工具?
下面介绍如何从文本字符串解析为 lxml 结构化数据类型。
蟒蛇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)
蟒蛇 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>
我使用 lxml 库,它很简单
>>> print(etree.tostring(root, pretty_print=True))
您可以使用 any 来执行该操作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
这是一个 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)
我在这里找到了如何解决常见的换行问题。