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

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值