python解析xml文件之xml.etree.cElementTree和xml.etree.ElementTree区别和基本使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kwame211/article/details/81901796

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()

猜你喜欢

转载自blog.csdn.net/kwame211/article/details/81901796