XMLファイルの基本構造
<?xml version="1.0" encoding="utf-8"?>
<root>
<element attribute='zokusei'>
<tag>text</tag>
</element>
</root>
・木構造。最上位に1つだけルート(root)があり、その下に複数の要素(element)が存在している
・また、それぞれの開始と終わりは<> </>となっており、下の階層の要素を挟むように位置している。
インポート
import xml.etree.ElementTree
データ読み込み
tree = ET.parse('file.xml')
root = tree.getroot()
# ファイルに拡張子がついて無かったり、テキストを読み込む際
with open('sample.txt',encoding = "utf-8") as file:
text = file.read()
root = ET.fromstring(text) # ET.XML()も同じ
データ抽出
# ルートノードの抽出
element = root.tag
# ノード属性の抽出
attribute = element.attrib
# ノードのテキストの抽出(&子ノードの抽出)
for child in root:
tag_text = child.text
参考サイト