我刚刚在Stackoverflow上发现了此方法以打印xml代码:
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)
但是我想将打印的内容放入变量中。 我尝试了最简单的方法:
data = Elementtree.dump(root)
print("==>", data)
但是它返回我“ ==>无” 就像:ElementTree.dump(root)无论什么都在打印。
感谢您的帮助
答案 0 :(得分:0)
data = Elementtree.tostring(root)
print("==>", data)