xml模塊

處理文檔:
Python - xml模塊_第1張圖片

            
              import xml.etree.ElementTree as ET

tree = ET.parse('xmlfile')    # ET.parse() 解析xml文檔
root = tree.getroot()        # 獲取根節點
print(root.tag)          # root.tag 獲取根節點標簽   這里是data
            
          

Python - xml模塊_第2張圖片

            
              for i in root:
    print(i.tag)        # 獲取根節點下的標簽
    print(i.attrib)     # 獲取根節點下的標簽屬性
            
          

標簽>>: country 、標簽屬性>>: {'name': 'Panama'}

Python - xml模塊_第3張圖片

同樣的 country 下也有標簽、屬性等:

Python - xml模塊_第4張圖片

也可以用for循環取數據:

Python - xml模塊_第5張圖片

被標簽包圍的數據取出來:

Python - xml模塊_第6張圖片

k.text

Python - xml模塊_第7張圖片

root.iter('year') 遍歷year節點:

Python - xml模塊_第8張圖片

修改year節點的屬性和值:

Python - xml模塊_第9張圖片
Python - xml模塊_第10張圖片

刪除:

Python - xml模塊_第11張圖片

運行后顯示:

Python - xml模塊_第12張圖片

新建一個xml文檔

Python - xml模塊_第13張圖片

代碼運行后:

Python - xml模塊_第14張圖片