漂亮地打印 xml 代码并放入变量中
Pretty print xml code and put in a variable
我刚刚在 Whosebug 上找到了这个打印 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)
但它 returns 我 "==> None"
就像:ElementTree.dump(root) 无论如何都在打印。
感谢您的帮助
data = Elementtree.tostring(root)
print("==>", data)
我刚刚在 Whosebug 上找到了这个打印 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)
但它 returns 我 "==> None" 就像:ElementTree.dump(root) 无论如何都在打印。
感谢您的帮助
data = Elementtree.tostring(root)
print("==>", data)