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")
原文地址:https://www.cnblogs.com/TKOPython/p/12322786.html