xml文件的读取、查询、修改、删除
import xml.etree.ElementTree as ET #因为xml.etree.ElementTree比较长,as用于取个别名 tree = ET.parse("xml_test") root = tree.getroot() print(root.tag) #遍历xml文档 for child in root: print(child.tag,child.attrib) for i in child: print(i.tag,i.text) #只遍历year节点 for node in root.iter('year'): print(node.tag,node.text) #修改year for node in root.iter('year'): #先遍历是否存在‘year’标签 new_year = int (node.text) + 1 #定义一个变量new_year,赋值为year整形的节点text值+1 node.text = str(new_year) #text值再转回字符串格式 node.set("updated","yes") #'updated'属性更新为‘yes' tree.write("xml_test") #重新写入文档 #删除排名大于50的国家 for country in root.findall('country'): rank = int(country.find('rank').text) if rank > 50: root.remove(country) tree.write('xml_test1')
被读取的xml_test
<data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year updated="no">2011</year> <gdppc>141100</gdppc> <neighbor direction="E" name="Austria" /> <neighbor direction="W" name="Switzerland" /> </country> <country name="Singapore"> <rank updated="yes">5</rank> <year updated="no">2014</year> <gdppc>59900</gdppc> <neighbor direction="N" name="Malaysia" /> </country> <country name="Panama"> <rank updated="yes">69</rank> <year updated="no">2014</year> <gdppc>13600</gdppc> <neighbor direction="W" name="Costa Rica" /> <neighbor direction="E" name="Colombia" /> </country> </data>
被修改后的xml_test
<data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year updated="yes">2012</year> <gdppc>141100</gdppc> <neighbor direction="E" name="Austria" /> <neighbor direction="W" name="Switzerland" /> </country> <country name="Singapore"> <rank updated="yes">5</rank> <year updated="yes">2015</year> <gdppc>59900</gdppc> <neighbor direction="N" name="Malaysia" /> </country> <country name="Panama"> <rank updated="yes">69</rank> <year updated="yes">2015</year> <gdppc>13600</gdppc> <neighbor direction="W" name="Costa Rica" /> <neighbor direction="E" name="Colombia" /> </country> </data>
新生成的xml_test1
<data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year updated="yes">2012</year> <gdppc>141100</gdppc> <neighbor direction="E" name="Austria" /> <neighbor direction="W" name="Switzerland" /> </country> <country name="Singapore"> <rank updated="yes">5</rank> <year updated="yes">2015</year> <gdppc>59900</gdppc> <neighbor direction="N" name="Malaysia" /> </country> </data>
输出:
data
country {'name': 'Liechtenstein'}
rank 2
year 2011
gdppc 141100
neighbor None
neighbor None
country {'name': 'Singapore'}
rank 5
year 2014
gdppc 59900
neighbor None
country {'name': 'Panama'}
rank 69
year 2014
gdppc 13600
neighbor None
neighbor None
year 2011
year 2014
year 2014