猿问
用Python漂亮地打印XML
用Python漂亮地打印XML
用Python打印XML的最佳方法(甚至是各种方法)是什么?
千巷猫影
浏览 1717
回答 3
3回答
喵喔喔
import xml.dom.minidom dom = xml.dom.minidom.parse(xml_fname) # or xml.dom.minidom.parseString(xml_string)pretty_xml_as_string = dom.toprettyxml()
0
0
0
qq_笑_17
另一个解决办法是借这,这个indent功能,用于自2.5以来内置到Python中的ElementTree库。如下所示: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
0
0
随时随地看视频
慕课网APP
相关分类
Python
我要回答