我用Python生成了一个又长又难看的XML字符串,需要通过漂亮打印程序进行过滤以使其更美观。
我找到了这篇帖子介绍了Python的漂亮打印程序,但是我必须将XML字符串写入文件才能读回来使用这些工具,如果可能的话,我想避免这种情况。
有哪些适用于字符串的Python漂亮工具可用?
我用Python生成了一个又长又难看的XML字符串,需要通过漂亮打印程序进行过滤以使其更美观。
我找到了这篇帖子介绍了Python的漂亮打印程序,但是我必须将XML字符串写入文件才能读回来使用这些工具,如果可能的话,我想避免这种情况。
有哪些适用于字符串的Python漂亮工具可用?
以下是将文本字符串解析为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>
etree.tounicode
方法解决了它。 - mut1naprint(etree.tostring(tree, pretty_print=True).decode())
。 - orodbhen我使用lxml库,里面很简单:
>>> print(etree.tostring(root, pretty_print=True))
etree
执行该操作,你可以通过程序生成,也可以从文件中读取。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
toprettyxml()
函数。如果它只是一个字符串,那么你需要先解析它才能漂亮地打印出来。 - Paul McMillanxml.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)