倒入模块
import xml.etree.ElementTree as ET
tree = ET.parse('xml_test')
root = tree.getroot()
xml模版
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank>4</rank>
<year>2009</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank>68</rank>
<year>2010</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
查询
for i in root:
# print('根节点',i.tag,i.attrib,i.text)
for j in i:
print('从节点',j.tag,j.attrib,j.text)
修改
for i in root.iter('year'):
new_year = int(i.text) + 100
i.text = str(new_year)
i.set('Rainy','wangxiaolong')
tree.write('xml_test.xml')
删除
for country in root.findall('country'):
rank = int(country.find('rank').text)
if rank > 50:
root.remove(country)
tree.write('bbb.xml')
生成一个XML文件
import xml.etree.ElementTree as ET
new_xml = ET.Element('Rainy')
name = ET.SubElement(new_xml,'name',attrib = {'enrolled':'yes'})
age = ET.SubElement(name,'age',attrib = {'checked':'no'})
sex = ET.SubElement(name,'sex')
sex.text = '222'
name1 = ET.SubElement(new_xml,'name1',attrib={'Rainyyyy':'wangwww'})
age = ET.SubElement(name1,'age')
sex = ET.SubElement(name1,'sex')
age.text = '18'
et = ET.ElementTree(new_xml). #生成编辑文档
et.write('ccc.xml',encoding='utf-8',xml_declaration=True) #保存到磁盘
ET.dump(new_xml)