zoukankan      html  css  js  c++  java
  • Python-操作XML文件

    一、python对XML文件的操作

      目录

        1、xml 创建

        2、xml 数据查询

        3、xml 数据修改

        4、xml 数据删除

    二、

      1、xml 创建

      

     1 import xml.etree.ElementTree as ET
     2 
     3 new_xml=ET.Element('personinfolist')   #最外面的标签名
     4 personinfo=ET.SubElement(new_xml,'personinfo',attrib={'enrolled':'aaa'}) #对应的参数是:父级标签是谁,当前标签名,当前标签属性与值
     5 name=ET.SubElement(personinfo,'name')
     6 name.text='xaoming'
     7 age=ET.SubElement(personinfo,'age',attrib={'checked':'yes'})
     8 age.text='23'
     9 
    10 
    11 
    12 personinfo2=ET.SubElement(new_xml,'personinfo',attrib={'enrolled':'bbb'})
    13 name=ET.SubElement(personinfo2,'name')
    14 name.text='xaokong'
    15 age=ET.SubElement(personinfo2,'age',attrib={'checked':'no'})
    16 age.text='20'
    17 
    18 et=ET.ElementTree(new_xml)
    19 et.write('text1.xml',encoding='utf-8',xml_declaration=True)#生成text1.xml

    2、xml 数据查询

     1 import xml.etree.ElementTree as ET
     2 
     3 tree=ET.parse('text1.xml')
     4 
     5 root=tree.getroot()
     6 
     7 print(root.tag)
     8 
     9 #遍历 xml 文档
    10 for i in root:
    11     print(i.tag,i.attrib)    # tag是指标签名,attrib 是指标签里的属性,text 是指标签内容
    12     for j in i:
    13         print(j.tag,j.attrib,j.text)
    14         for k in j:
    15             print(k.tag,k.attrib,k.text)
    16 
    17 #只遍历 year 标签
    18 for w in root.iter('year'):  #只遍历指定标签
    19     print(w.tag,w.text)

    3、xml 数据修改

     1 import xml.etree.ElementTree as ET
     2 
     3 tree=ET.parse('text1.xml')
     4 
     5 root=tree.getroot()
     6 
     7 print(root.tag)
     8 
     9 #修改 xml
    10 for node in root.iter('year'):  #要修改的标签
    11     new_year=int(node.text)+1
    12     node.text=str(new_year)
    13     node.set('updsted_by','kong')  #给这个标签(year)添加新的属性 key:value
    14 
    15 tree.write('text1.xml')     #再吧数据写回去

    4、xml数据删除

    import xml.etree.ElementTree as ET
    
    tree=ET.parse('text1.xml')
    
    root=tree.getroot()
    
    
    for country in root.findall('country'):   #会取这个标签所有的数据
        rank=int(country.find('rank').text)
        if rank > 50:
            root.remove(country)    #删除数据
    
    
    tree.write('output.xml')  #再把数据写回文件

    学习无止境,初心要笃行!!!

  • 相关阅读:
    @RequestParam注解使用:Name for argument type [java.lang.String] not available, and parameter name information not found in class file either.
    cglib动态代理导致注解丢失问题及如何修改注解允许被继承
    springboot Autowired BeanNotOfRequiredTypeException
    git根据用户过滤提交记录
    不同包下,相同数据结构的两个类进行转换
    How to use Jackson to deserialise an array of objects
    jooq实践
    java如何寻找main函数对应的类
    Python--matplotlib
    Python 和 Scikit-Learn
  • 原文地址:https://www.cnblogs.com/km-thonder/p/12577489.html
Copyright © 2011-2022 走看看