はじめに
今日はXMLのデータをpython script で読むためのメモです。本当にただのメモ。
内容
標準ライブラリを使ってできます。
なのですが、とりあえず動かしてみたメモを。
例
全くXMLを分かっていないのですが、xml.etree.ElementTree
というのを使えばできるようです。
- 木構造のデータを fromstring で読み込める。
- root も child もtag と attribute を持っていて、.tag, .attrib でアクセスできる
- 値?は .text で参照できる。
iterator でアクセスする場合もあるけれど、今回は下記の単純なサンプルなので必要なった。
xml_string = \
"""<?xml version="1.0" encoding="UTF-8"?>
<calibration>
<projection>frame</projection>
<width>5456</width>
<height>3632</height>
<f>3683.29</f>
<cx>-5.730</cx>
<cy>-38.810</cy>
<date>2010-01-01T12:23:12Z</date>
</calibration>
"""
import xml.etree.ElementTree as ET
root = ET.fromstring(xml_string)
print( f"root={root}")
print(f"root.tag={root.tag} .attrib={root.attrib} .text={root.text}")
for child in root:
print(f"child.tag={child.tag} .attrib={child.attrib} .text={child.text}")
実行結果
$ python3 test_xml_string_parse.py
root=<Element 'calibration' at 0x7f326cb487c0>
root.tag=calibration .attrib={} .text=
child.tag=projection .attrib={} .text=frame
child.tag=width .attrib={} .text=5456
child.tag=height .attrib={} .text=3632
child.tag=f .attrib={} .text=3683.29
child.tag=cx .attrib={} .text=-5.730
child.tag=cy .attrib={} .text=-38.810
child.tag=date .attrib={} .text=2010-01-01T12:23:12Z
何の面白味もないが、読み込めたのは確認できた。
root からiterate 可能な要素として読んでいるので、番号のインデックスでもアクセスできます。
In [10]: root[1].text
Out[10]: '5456'
また、ファイルから直接に読むこともできます。
mydata.xml
<?xml version="1.0" encoding="UTF-8"?>
<calibration>
<projection>frame</projection>
<width>5456</width>
<height>3632</height>
<f>3683.29</f>
<cx>-5.730</cx>
<cy>-38.810</cy>
<date>2010-01-01T12:23:12Z</date>
</calibration>
というファイルを、
tree = ET.parse('mydata.xml')
root = tree.getroot()
と読みます。
まとめ
今回、ただ読めただけなのだが、それ以上なし。
何かあればメモを足していきます。明日の仕事もこれでできそうな気がしています。