在Python中漂亮地打印XML
在Python中打印xml的最佳方式(甚至是各种方式)是什么?
import xml.dom.minidom
xml = xml.dom.minidom.parse(xml_fname) # or xml.dom.minidom.parseString(xml_string)
pretty_xml_as_string = xml.toprettyxml()
lxml是最近更新的,并包含一个漂亮的打印功能
import lxml.etree as etree
x = etree.parse("filename")
print etree.tostring(x, pretty_print=True)
查看lxml教程:http://lxml.de/tutorial.html
另一个解决方案是借用这个indent
函数,用于2.5以来内置到Python中的ElementTree库。 以下是这样的内容:
from xml.etree import ElementTree
def indent(elem, level=0):
i = "n" + level*" "
j = "n" + (level-1)*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for subelem in elem:
indent(subelem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = j
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = j
return elem
root = ElementTree.parse('/tmp/xmlfile').getroot()
indent(root)
ElementTree.dump(root)
链接地址: http://www.djcxy.com/p/37155.html