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')

         

  • 相关阅读:
    模拟打车
    atm转账
    python字符串,列表,字典,集合的常用方法
    while和for的简单使用
    数据库的基本命令
    jmeter监控linux的性能
    jmeter的错误解决Cannot create PoolableConnectionFactory (Access denied for user 'root'@'localhost' (using password: YES))
    jmeter的正则参数化
    jmeter的参数化关联
    使用Python解析JSON
  • 原文地址:https://www.cnblogs.com/my-love-is-python/p/9076654.html
Copyright © 2011-2022 走看看