1、解析速度:ElementTree在 Python 標准庫中有兩種實現。一種是純 Python 實現例如 xml.etree.ElementTree ,另外一種是速度快一點的 xml.etree.cElementTree 。你要記住: 盡量使用 C 語言實現的那種,因為它速度更快,而且消耗的內存更少。
2、調試區別
使用cElementTree的話,在pycharm的debug模式下,是看不到內容的
使用ElementTree,可以看到豐富信息,子節點,子節點的子節點等等,非常方便開發
3、所以對於線上產品應該使用下面這種的方式,但是開發的時候,應該使用 import xml.etree.ElementTree as ET
try: import xml.etree.cElementTree as ET except ImportError: import xml.etree.ElementTree as ET
tree = ET.parse(config_file)
tree = ET.parse(config_file)或者tree = ET.fromstring(string),可以從文件或者字符串中解析到xml的結構
基本使用:
1、可以從文件或者字符串中解析到xml的結構
從硬盤的文件解析
import xml.etree.ElementTree as ET tree = ET.parse('country_data.xml') root = tree.getroot()
直接從字符串解析:
root = ET.fromstring(country_data_as_string)
2、查找元素:
Element.findall()
finds only elements with a tag which are direct children of the current element. Element.find()
finds the first child with a particular tag, and Element.text
accesses the element’s text content. Element.get()
accesses the element’s attributes:
3、修改元素:
增加新節點: Element.append()
增加或者修改屬性:Element.set()
修改內容: Element.text
創建xml文件: ElementTree.write()
刪除節點:Element.remove()
2、
參考:
1、https://www.biaodianfu.com/python-xml.html
2、https://docs.python.org/2/library/xml.etree.elementtree.html
3、http://effbot.org/zone/element.htm