首页 > 其他 > 详细

xml模块

时间:2020-02-17 19:15:12      阅读:75      评论:0      收藏:0      [点我收藏+]
<?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")

 

xml模块

原文:https://www.cnblogs.com/TKOPython/p/12322786.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!