ElementTreeは、XMLをファイルやテキストから読み込んだり、加工したり、保存したりするためのモジュールです。
文字列のXMLデータの読み込み
from xml.etree.ElementTree import *
xml = """
<page version="1.0" no="1">
<items>
<item type="type1">
<name>Item1</name>
<price>100</price>
</item>
<item type="type2">
<name>Item2</name>
<price>200</price>
</item>
</items>
</page>
"""
# ルート要素を取得(Element型)
e = fromstring(xml)
#---XMLデータの参照-------------------------------
print("content-type: text/html; charset=utf-8\n");
print(e.tag) #「page」を表示
print(e.get("version")) #「1.0」を表示
print(e.get("yen", "100")) #「100」を表示
print(e.keys()) #['version', 'no']を表示
print(e.items()) # [('version', '1.0'), ('no', '1')]を表示
ElementTreeを使う上で必要なのがElementというオブジェクトです。
このElementTree型のオブジェクトはXMLファイルからデータを読み込んだり、書き込んだりする際に利用されるラッパークラスです。
XMLを表す文字列からElementオブジェクトを作成するには、fromstringメソッド(19行目)を呼び出します。
XMLファイルデータの読み込み
<page version="1.0" no="1">
<items id="1">
<item type="type1">
<name n="1">Item1</name>
<price p="1">2000</price>
</item>
<item type="type2">
<name n="2">Item2</name>
<price p="2">2300</price>
</item>
</items>
</page>
from xml.etree.ElementTree import *
tree = parse("sample.xml") # 返値はElementTree型
e = tree.getroot() # ルート要素を取得(Element型)
#---XMLデータの参照-------------------------------
print("content-type: text/html; charset=utf-8\n");
print(e.tag) #「page」を表示
print(e.get("version")) #「1.0」を表示
print(e.get("yen", "100")) #「100」を表示
print(e.keys()) #['version', 'no']を表示
print(e.items()) # [('version', '1.0'), ('no', '1')]を表示
parseメソッドを呼んで、その後にgetrootメソッドを呼べばElement型のルート要素が取得できます。
XMLデータの取得
※上記のtest.pyの出力の場合
出 力 | ||
---|---|---|
要素のタグを取得 | e.tag | page |
属性の取得 | e.attrib | {‘version’: ‘1.0’, ‘no’: ‘1’} |
引数で指定した属性の取得 | e.get(“version”) | 1.0 |
デフォルトを指定して属性を取得 | e.get(“yen”, “100”) | 100 |
属性名のリスト取得 | e.keys() | [‘version’, ‘no’] |
(属性, 値)形式タプルのリスト取得 | e.items() | [(‘version’, ‘1.0’), (‘no’, ‘1’)] |
要素内の文字列を取得 | .text | 子ノード(要素)の取得の37行目を参照 |
子ノード(要素)の取得
for child in e:
print(child.tag, child.attrib)
# items {'id': '1'} を表示
上記は第2階層の子ノード取得になりますが、子ノードは入れ子になっており、インデックスで第2階層以下の子ノードも指定して取得できます。
for child in e:
print(child[0].tag, child[0].attrib)
# item {'type': 'type1'} を表示
for child in e:
print(child[0][0].tag, child[0][0].attrib)
# name {'n': '1'} を表示
for child in e:
print(child[0][1].tag, child[0][1].attrib)
# price {'p': '1'} を表示
for child in e:
print(child[1].tag, child[1].attrib)
# item {'type': 'type2'} を表示
for child in e:
print(child[1][0].tag, child[1][0].attrib)
# name {'n': '2'} を表示
for child in e:
print(child[1][1].tag, child[1][1].attrib)
# price {'p': '2'} を表示
for child in e:
print(child[1][1].tag, child[1][1].attrib, child[1][1].text)
# price {'p': '2'} 2300 を表示
要素の検索
Element.iterメソッドは引数に指定した要素の全体を取得します。
for child in e.iter('item'):
print(child.attrib)
# {'type': 'type1'} {'type': 'type2'} を表示
上記で引数を指定しない場合はすべての要素の属性を表示します。