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

    <?xml version="1.0"?>
    <data>
        <country name="Liechtenstein">
            <rank updated="yes">2</rank>
            <year>2008</year>
            <gdppc>141100</gdppc>
            <neighbor name="Austria" direction="E"/>
            <neighbor name="Switzerland" direction="W"/>
        </country>
        <country name="Singapore">
            <rank updated="yes">5</rank>
            <year>2011</year>
            <gdppc>59900</gdppc>
            <neighbor name="Malaysia" direction="N"/>
        </country>
        <country name="Panama">
            <rank updated="yes">69</rank>
            <year>2011</year>
            <gdppc>13600</gdppc>
            <neighbor name="Costa Rica" direction="W"/>
            <neighbor name="Colombia" direction="E"/>
        </country>
    </data>
    import xml.etree.ElementTree as ET
    
    #先解析xmlapp文档
    tree = ET.parse("xmlapp")
    #获取根目录<data>
    root = tree.getroot()
    print(root.tag)
    
    #遍历data
    #------------------------------查询-------------------------
    for data in root:              #attrib  属性
        print(data.tag,data.attrib)  #遍历data下的标签和属性
        #获取data下的所有标签和文本
        for child in data:
            print(child.tag,child.text)
    
    
    #只查看某一个标签和文本
    for itr in root.iter("year"):
        print(root.iter("year").text)
    
    #------------------------------修改-------------------------
    for itr in root.iter("year"):      #修改text时间
        it = int(itr.text)+1
        itr.text = str(it)
        itr.set("abc","yes")    #也可以设置标签
    tree.write("xmlapp")
    
    #------------------------------删除-------------------------
    for node in root.findall("country"):
        # yer = int(node.text.find("year"))
        yer = int(node.find("year").text)   #查找到要删除的位置
        if yer > 2009:
            root.remove(node)
        # print(yer)
    
    tree.write("xmlapp")
  • 相关阅读:
    辞职后的第二个星期
    最近似乎应该休眠了.
    文件.二进制转换
    AVL树
    ajax 的同步和异步
    在SQL Server实现最短路径的搜索
    网页嵌套com例子
    Vs2005 dll 设置def导出函数
    [转]ATL开发一个ActiveX
    Atl COM发布与优化
  • 原文地址:https://www.cnblogs.com/TKOPython/p/12322786.html
Copyright © 2011-2022 走看看