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

摘要:
你应该记住:尽量使用C语言,因为它更快,消耗更少的内存。

1、解析速度:ElementTree在 Python 标准库中有两种实现。一种是纯 Python 实现例如 xml.etree.ElementTree ,另外一种是速度快一点的 xml.etree.cElementTree 。你要记住: 尽量使用 C 语言实现的那种,因为它速度更快,而且消耗的内存更少。

2、调试区别

使用cElementTree的话,在pycharm的debug模式下,是看不到内容的

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

使用ElementTree,可以看到丰富信息,子节点,子节点的子节点等等,非常方便开发

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

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

免责声明:文章转载自《python解析xml文件之xml.etree.cElementTree和xml.etree.ElementTree区别和基本使用》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Linux权限问题(2)-unzip引发的权限问题小程序页面传值e.currentTarget下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

python图像处理之pyocr

使用pyocr类库进行ocr识别,其中tools为’Tesseract’ #!/usr/bin/env python #coding=utf-8 __author__ = 'zhangdebin' from PIL import Image import sys import pyocr tools = pyocr.get_available_to...

jmeter调用Python

1.下载插件 链接:https://pan.baidu.com/s/1yfr9qTYf396VXi5itLOKhQ 提取码:28j8 2.下载成功后放到jmeter相关目录下 3.来一段脚本试试  3.1 先设置一个自定义变量 3.2 编写脚本 import sysreload(sys)sys.setdefaultencoding('utf8') #...

python机器学习sklearn 岭回归(Ridge、RidgeCV)

  1、介绍     Ridge 回归通过对系数的大小施加惩罚来解决 普通最小二乘法 的一些问题。 岭系数最小化的是带罚项的残差平方和,          其中,α≥0α≥0 是控制系数收缩量的复杂性参数: αα 的值越大,收缩量越大,这样系数对共线性的鲁棒性也更强。        2、参数         alpha:{float,array-like}...

postman 断言学习

请求 url :https://www.v2ex.com/api/nodes/show.json?name=python get请求 postman发起请求并做断言 断言: tests["Body matches string"] = responseBody.has("这里讨论各种 Python 语言编程话题,也包括 Django,Tornado 等框...

利用pyinstaller打包加密Python项目

  最近用Python给媳妇写了两个小项目,给解决了她的每天重复的一些人工操作。媳妇很开心,但是问题来了,她是个Python小白,对她来说,需要安装配置Python环境和一大堆第三方模块是个麻烦事儿。而且后续把这些工作交接给别人的话,一是又需要重新安装Python环境,二是我辛苦给她写的源码就这样暴露了。   为了解决这个问题,于是就开始百度。果然Pyth...

python测试开发django(33)--xadmin注册表信息

前言 xadmin后台如果要对表的内容增删改查,跟之前的admin.py文件里面写注册表信息一样,需在admin.py同一级目录新建一个adminx.py的文件。 然后在admin.py文件控制页面上需显示的内容。 models模块 models模块跟之前设计表是一样的,在models.py文件设计表的字段显示,以Studentts表为例。 # codin...