python ElementTree 输出带缩进格式的xml string

在使用xml.etree.ElementTree将xml内容作为一个字符串输出时,模块提供的tostring函数直接将xml内容输出为一整行字符串,没有对不同节点进行分行缩进显示的功能。

考虑如下的示例:

1 import xml.etree.ElementTree as ET
2 
3 root_node = ET.Element('root')
4 child_node_1 = ET.SubElement(root_node, 'child_1')
5 child_node_1.text = 'child_1'
6 child_node_2 = ET.SubElement(root_node, 'child_2')
7 child_node_2.text = 'child_2'
8 print ET.tostring(root_node)

最后输出的字符串为:

<root><child_1>child_1</child_1><child_2>child_2</child_2></root>

 查阅网上的资料,使用如下的函数,对模块的内容预先进行额外处理,从而满足输出的格式需求。

 1 def indent(elem, level=0):
 2     i = "\n" + level*"\t"
 3     if len(elem):
 4         if not elem.text or not elem.text.strip():
 5             elem.text = i + "\t"
 6         if not elem.tail or not elem.tail.strip():
 7             elem.tail = i
 8         for elem in elem:
 9             indent(elem, level+1)
10         if not elem.tail or not elem.tail.strip():
11             elem.tail = i
12     else:
13         if level and (not elem.tail or not elem.tail.strip()):
14             elem.tail = i

即在调用tostring函数输出时,预先对根节点调用indent函数,上述示例修改为:

1 root_node = ET.Element('root')
2 child_node_1 = ET.SubElement(root_node, 'child_1')
3 child_node_1.text = 'child_1'
4 child_node_2 = ET.SubElement(root_node, 'child_2')
5 child_node_2.text = 'child_2'
6 indent(root_node)    # 增加对根节点的额外处理
7 print ET.tostring(root_node

这样即可以输出如下的字符串:

<root>
	<child_1>child_1</child_1>
	<child_2>child_2</child_2>
</root>

 

参考资料: https://pycoders-weekly-chinese.readthedocs.org/en/latest/issue6/processing-xml-in-python-with-element-tree.html

                  http://stackoverflow.com/questions/749796/pretty-printing-xml-in-python

 

posted on 2013-12-06 21:37  vanilla_sky  阅读(8088)  评论(1编辑  收藏  举报

导航