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)
这里有一个Python3解决方案,它消除了难看的换行符问题(大量的空白),并且它只使用标准库,这与大多数其他实现不同。您提到您已经有了一个xml字符串,所以我假设您使用了
xml.dom.minidom.parseString()
使用以下解决方案,您可以避免先写入文件:
我找到了如何解决常见的换行问题here
我使用lxml库,在那里它非常简单
您可以使用任何
etree
执行该操作,您可以通过编程方式生成该操作,也可以从文件读取该操作如果您使用的是PyXML中的DOM,那么
打印到标准输出的,除非指定备用流
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:
Python 3:
产出:
相关问题 更多 >
编程相关推荐