XML是實現不同語言或程式之間進行資料交換的協議,XML檔案格式如下:
<data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year age="25">2033</year> <gdppc>141100</gdppc> <neighbor direction="E" name="Austria" /> <neighbor direction="W" name="Switzerland" /> </country> <country name="Singapore"> <rank updated="yes">5</rank> <year age="25">2036</year> <gdppc>59900</gdppc> <neighbor direction="N" name="Malaysia" /> </country> <country name="Panama"> <rank updated="yes">69</rank> <year age="25" type="date">2036</year> <gdppc>13600</gdppc> <neighbor direction="W" name="Costa Rica" /> <neighbor direction="E" name="Colombia" /> </country></data>
我們建立操作XMl對象有2種建立方法 如下
# -*- coding: utf-8 -*-from xml.etree import ElementTree as ET#開啟檔案 讀取XML內容 第一種建立方法str_xml= open('data.xml','r').read()#將字串解析成xml特殊對象,root代指xml檔案的根節點root = ET.XML(str_xml) #dataprint(root) #返回一個對象#輸出 <Element 'data' at 0x1006feb50># 第二種建立方法# 直接解析xml檔案tree = ET.parse('data.xml')#擷取xml檔案的根節點root = tree.getroot()print(root) #輸出 <Element 'data' at 0x101821650>我們可以查看data.xml所有的節點
#便利所有的子節點for child in root: #第二層 print(child.tag,child.attrib) #輸出一個元組 #對第二層節點下面的子節點進行便利 for i in child: print(i.tag,i.attrib)
擷取指定的節點
#擷取xml中的制定節點for child in root.iter('year'): print(child.tag,child.attrib)
對XML中的操作一般是在記憶體中進行的,不會影響到檔案中的內容,因此我們在記憶體中寫完之後需要重新寫入檔案
#對xml檔案進行操作 增刪改查for node in root.iter('year'): # 將year內容+10 new_year = int(node.text)+10 node.text = str(new_year) # 設定屬性 node.set('name','eric') node.set('age','25') #刪除屬性 del node.attrib['age']#儲存到檔案tree = ET.ElementTree(root)tree.write('data.xml',encoding='utf-8')#刪除節點for country in root.findall('country'): # 擷取每一個country節點下rank節點的內容 rank = int(country.find('rank').text) if rank > 50: root.remove(country) #會刪除掉 整個country節點和下面的內容#儲存到檔案tree = ET.ElementTree(root)tree.write('data.xml',encoding='utf-8')