如何使用 Python 處理 XML 格式檔案 (Process XML file With Python)


  1. 範例程式碼
    1. 載入 XML
    2. 取得標籤資訊 (TagName, Value, Attribute)
    3. 尋找元素 (Find, FindAll)
    4. 迭代尋找 (Iter)
    5. 設定值 (text, set)
    6. 建立元素與將元素字串化 (Element, SubElement, Dump)
    7. 迭代取出值
  2. 參考資料

最近有處理 XML 檔案的需求,第一時間想到的就是 Python ,上一次處理 XML 已經是四、五年前的事情了,當時雖然有已經在工作上使用 Python ,但對於物件導向以及模組的運用仍是十分陌生,記得當時處理 XML 的方式就是當成字串來處理,現在想起不經莞爾。

而這次同樣使用 Python 的處理 XML ,搭配著 Built-in Battery 的 ElementTree 模組,處理起來行雲流水十分順利,特此筆記以供日後有同樣的需求時參考。

logo

範例程式碼

載入 XML

import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml') # From file
tree = ET.fromstring(xmlStrings) # From XML String
root = tree.getroot()

取得標籤資訊 (TagName, Value, Attribute)

print(root.tag)
print(root.find('element').text)
print(root.find('element').attrib)

尋找元素 (Find, FindAll)

Find : 找到指定節點下的第一個特定節點
Findall : 找到指定節點下的所有特定節點

for ele in root.findall('Element'):
  ...

迭代尋找 (Iter)

找出節點下的符合的子節點、孫節點。

for ele in root.iter('Element'):
  ...

設定值 (text, set)

root.text = 'textValue' # Set text
root.set('attr', value)  # Set attrib

建立元素與將元素字串化 (Element, SubElement, Dump)

a = ET.Element('a')
b = ET.SubElement(a, 'b')
c = ET.SubElement(a, 'c')
d = ET.SubElement(c, 'd')
ET.dump(a)
'<a><b /><c><d /></c></a>'

迭代取出值

xmlString = '<a><b>1<c>2<d/>3</c></b>4</a>'
tree = ET.fromstring(xmlString)
"".join(tree.itertext()) 
'1234'

參考資料