Python - xml模塊

xml模塊

處理文檔:
Python - xml模塊

import xml.etree.ElementTree as ET

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

Python - xml模塊

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

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

Python - xml模塊

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

Python - xml模塊

也可以用for循環取數據:

Python - xml模塊

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

Python - xml模塊

k.text

Python - xml模塊

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

Python - xml模塊

修改year節點的屬性和值:

Python - xml模塊
Python - xml模塊

刪除:

Python - xml模塊

運行後顯示:

Python - xml模塊

新建一個xml文檔

Python - xml模塊

代碼運行後:

Python - xml模塊

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章