用Python漂亮地打印XML用Python打印XML的最佳方法(甚至是各种方法)是什么?
3 回答
喵喔喔
TA贡献1735条经验 获得超5个赞
import xml.dom.minidom dom = xml.dom.minidom.parse(xml_fname) # or xml.dom.minidom.parseString(xml_string)pretty_xml_as_string = dom.toprettyxml()
qq_笑_17
TA贡献1818条经验 获得超7个赞
indent
from xml.etree import ElementTreedef 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)
添加回答
举报
0/150
提交
取消