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