LoginSignup
1
1

More than 1 year has passed since last update.

【Python】XMLのデータを読む

Last updated at Posted at 2021-10-19

はじめに

今日は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()

と読みます。

まとめ

今回、ただ読めただけなのだが、それ以上なし。
何かあればメモを足していきます。明日の仕事もこれでできそうな気がしています。

1
1
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
1
1