zoukankan      html  css  js  c++  java
  • xml 创建 和 处理 及其修改

    #创建xml

    import xml.etree.ElementTree as ET

    new_xml = ET.Element('namelist') 

    personinfo = ET.SubElement(new_xml, 'personinfo', attrib = {'enroll' :yes})

    age = ET.SubElement(personinfo,'name', attrib = {'check':'no'})

    name =  ET.SubElement(personinfo,'age', attrib = {'check':'no'})

    name.text = 'Alex li' 

    age.text = '23' 

    prosoninfo2 =  ET.SubElement(new_xml, 'personinfo', attrib = {'enroll' :yes})

    age = ET.SubElement(personinfo2,'name', attrib = {'check':'no'})

    name =  ET.SubElement(personinfo2,'age', attrib = {'check':'no'})

    name.text = 'Alex li' 

    age.text = '23'

    et = ET.ElementTree(new_xml)

    et.write('test.xml', encoding = 'utf-8), xml_declaration = True

    ET.dump(new_xml)

    #xml 打开和遍历

    Import xml.etree.ElementTree as ET 

    tree = ET.parse('xmltest.xml') #打开文件

    root = tree.getroot() #获取根目录

    print(root.tag)  #获取名称 

    for child in root:

         print(child.tag, child.attrib) 

         for i  in child:

              print(i.tag, i.text, i.attrib)

    for node in root.iter('year'):  #只遍历year节点

          print(node.tag, node.text)

    # xml修改 

    import xml.etree.ElementTree as ET

    tree = ET.parse('xmltest.xml')
    root = tree.getroot()

    for node  in root.iter('year'):
         new_year = int(node.text) + 1

         node.text = str(new_year)

         node.set = ('update', 'yes') 

    for country in root.findall('country')

           rank = int(country.find('rank').text)

           if rank > 50

           root.remove(country) 

    tree.wirte('output.xml')

         

  • 相关阅读:
    BZOJ3832: [Poi2014]Rally(拓扑排序 堆)
    UVAlive6807 Túnel de Rata (最小生成树)
    UVAlive6800The Mountain of Gold?(负环)
    cf623A. Graph and String(二分图 构造)
    BZOJ4144: [AMPPZ2014]Petrol(最短路 最小生成树)
    cf605D. Board Game(BFS 树状数组 set)
    为什么要去创业?
    后缀数组练习题若干
    Android开发 之 我的jar包引用方法
    IBM-ETP 实训项目前一天
  • 原文地址:https://www.cnblogs.com/my-love-is-python/p/9076654.html
Copyright © 2011-2022 走看看