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

      

      

     
  • 相关阅读:
    mysql中cast() 和convert()的用法讲解
    li内有span需要右浮的问题
    svn检出项目
    vue中的 ref 和 $refs
    for in 循环 和for循环 for of循环
    setInterval()、clearInterval()、setTimeout()和clearTimeout() js计数器方法(还有第三个参数)
    利用history.pushState()实现页面无刷新更新
    函数isNaN() parseFloat() parseInt() Math对象
    一个关于margin-top的问题
    vue 父子组件之间传参
  • 原文地址:https://www.cnblogs.com/Roc-Atlantis/p/8868064.html
Copyright © 2011-2022 走看看