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

     

猜你喜欢

转载自www.cnblogs.com/my-love-is-python/p/9076654.html