LoginSignup
0
0

Python × XML -ElementTree XML APIの使い方-

Last updated at Posted at 2024-01-04

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

参考サイト

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0