zoukankan      html  css  js  c++  java
  • xml处理模块

    1.root是节点,起始的数据。

    child.tag 和i.tag 返回的都是经过for循环得到的数据,后面的child.attrib和i.text是字符串输出格式。attrib是字典,text是文本。

    import xml.etree.ElementTree as ET
    
    tree = ET.parse("xml test")    #打开xml test 文件
    
    root = tree.getroot()
    
    print(root)
    
    print(root.tag)   # 输出为data
    for child in root:
        print("------------------",child.tag,child.attrib)
        for i in child:
            print(i.tag,i.text)  


    结果如下:
    <Element 'data' at 0x00000254E9B47638data>
    data

    ------------------ country {'name': 'Liechtenstein'}
    rank 2
    year 2008
    gdppc 141100
    neighbor None
    neighbor None
    ------------------ country {'name': 'Singapore'}
    rank 5
    year 2011
    gdppc 59900
    neighbor None
    ------------------ country {'name': 'Panama'}
    rank 69
    year 2011
    gdppc 13600
    neighbor None
    neighbor None                                                                                
                                                                                         
    ----------------------------------------------------华丽的分割线-------------------------------------------------------------

    想获取root里的某一项属性,可以通过iter。

    for node in root.iter("year"):
        print(node.tag,node.text)
        
    # year 2008
    # year 2011
    # year 2011
                                                                                                                                       

    修改xml里的值


    for node in root.iter("year"):
        new_node = int(node.text) + 1
        node.text = str(new_node)
        node.set("updated","yes")
    
    tree.write("xml test")
    

    删除rank点数大于50的

    for country in root.findall("country"):
        rank = int(country.find('rank').text)
        if rank > 50:
            root.remove(country)
    
    tree.write("output.xml")
    

      

      

     
  • 相关阅读:
    简单字典操作
    字符串操作
    2017年10月7日
    循环列表练习
    Zabbix4.0系统告警"Zabbix agent on Zabbix server is unreachable for 5 minutes"
    Zabbix4.0系统告警“Zabbix server is not running”
    FreeRADIUS使用了在Cisco IOS配置示例的管理访问
    Cisco AAA Configuration
    使用工具Csvde导出域中所有用户信息
    McAfee Agent卸载方法
  • 原文地址:https://www.cnblogs.com/Roc-Atlantis/p/8868064.html
Copyright © 2011-2022 走看看