概要
Webサイトから取得したXMLデータを読み込み、編集を行うことがあります。
以下のXMLファイルの読み込みを行います。
xmlSample.xml
Pythonソースコード
import xml.etree.ElementTree as ET
tree = ET.parse('./xmlSample.xml')
root = tree.getroot()
for child in root:
print(child.tag)
print(child.attrib)
解説
import xml.etree.ElementTree as ET
標準ライブラリのため、インストールは不要です。
tree = ET.parse('./xmlSample.xml')
XMLファイルを読み込みます。
root = tree.getroot()
XMLのROOT要素を取得します。
for child in root:
取得したROOT要素の子要素を出力します。
name
{'id': 'X01'}
name
{'id': 'X02'}
出力結果になります。
所感
XMLは設定ファイルに使用したり、WebからXML形式でファイルを取得したりした際に、XMLをプログラムで読み込む場合があります。