zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    date日期格式化
    表单解析模块formidable
    express-session模块
    密码加密模块bcrypt
    后端数据验证模块Joi
    mongoose-sex-page分页模块
    决策树算法及应用
    朴素贝叶斯分类
    实验二 K-邻近
    实验一 感知器及其应用
  • 原文地址:https://www.cnblogs.com/shengulong/p/8137893.html
Copyright © 2011-2022 走看看