2024-04-26 03:22:20 发布
网友
我用python生成了一个又长又难看的XML字符串,我需要通过漂亮的打印机来过滤它,以便看起来更好。
我为python漂亮的打印机找到了this post,但是为了使用这些工具,我必须将XML字符串写入一个要读回的文件中,如果可能的话,我希望避免使用这些工具。
哪些python漂亮的字符串工具可用?
我使用lxml库
>>> print(etree.tostring(root, pretty_print=True))
您可以使用任何etree执行该操作,您可以以编程方式生成该操作,也可以从文件中读取该操作。
etree
如果您使用来自PyXML的DOM,它是
import xml.dom.ext xml.dom.ext.PrettyPrint(doc)
打印到标准输出,除非指定备用流。
http://pyxml.sourceforge.net/topics/howto/node19.html
要直接使用minidom,需要使用toprettyxml()函数。
toprettyxml()
http://docs.python.org/library/xml.dom.minidom.html#xml.dom.minidom.Node.toprettyxml
下面是如何将文本字符串解析为lxml结构化数据类型。
Python2:
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)
Python3:
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库
您可以使用任何
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结构化数据类型。
Python2:
Python3:
输出:
相关问题 更多 >
编程相关推荐