python xml etree_python解析xml文件之xml.etree.cElementTree和xml.etree.ElementTree区别和基本使用...
1、解析速度:ElementTree在 Python 標(biāo)準(zhǔn)庫(kù)中有兩種實(shí)現(xiàn)。一種是純 Python 實(shí)現(xiàn)例如 xml.etree.ElementTree ,另外一種是速度快一點(diǎn)的 xml.etree.cElementTree 。你要記住: 盡量使用 C 語(yǔ)言實(shí)現(xiàn)的那種,因?yàn)樗俣雀?#xff0c;而且消耗的內(nèi)存更少。
2、調(diào)試區(qū)別
使用cElementTree的話,在pycharm的debug模式下,是看不到內(nèi)容的
使用ElementTree,可以看到豐富信息,子節(jié)點(diǎn),子節(jié)點(diǎn)的子節(jié)點(diǎn)等等,非常方便開發(fā)
3、所以對(duì)于線上產(chǎn)品應(yīng)該使用下面這種的方式,但是開發(fā)的時(shí)候,應(yīng)該使用 import xml.etree.ElementTree as ET
try:importxml.etree.cElementTree as ETexceptImportError:import xml.etree.ElementTree as ET
tree = ET.parse(config_file)
tree = ET.parse(config_file)或者tree = ET.fromstring(string),可以從文件或者字符串中解析到xml的結(jié)構(gòu)
基本使用:
1、可以從文件或者字符串中解析到xml的結(jié)構(gòu)
從硬盤的文件解析
importxml.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、修改元素:
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
總結(jié)
以上是生活随笔為你收集整理的python xml etree_python解析xml文件之xml.etree.cElementTree和xml.etree.ElementTree区别和基本使用...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 成都大熊猫基地可以带吃的吗
- 下一篇: python控制手机自动刷新闻_Pyth