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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM