• 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

  • 相关阅读:
    Quartus II -----破解
    博客诞生
    OpenMPI 学习笔记(一)并行计算机和分布式计算
    信息安全(1):安全策略
    认证
    SSL/TLS 和Https
    IPSec 网络协议安全
    C# 快速高效率复制对象另一种方式 表达式树
    C语言学习指针和数组2
    C语言学习二维数组
  • 原文地址:https://www.cnblogs.com/shengulong/p/8137893.html
Copyright © 2020-2023  润新知