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")
    

      

      

     
  • 相关阅读:
    jarsigner 签名android apk
    弱网络环境下,网络性能优化
    android 中handler的用法分析 (二)
    Mac 上面使用SVN的攻略
    android studio 编译加速
    Https 公钥、私钥、证书
    android sudio 打包资料汇总
    android studio 中查找代码中的硬编码
    ./adb: cannot execute binary file:
    android OOM分析工具LeakCanary
  • 原文地址:https://www.cnblogs.com/Roc-Atlantis/p/8868064.html
Copyright © 2011-2022 走看看