LoginSignup
2
1

More than 3 years have passed since last update.

Pythonチュートリアルを参考にxmlファイル読み込み

Last updated at Posted at 2020-07-12
data3.xml
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

findall 同じ子ノードすべてを参照する

findやfindallでほしいタグを指定する
以下ではすべてのcountryタグを取得する

from xml.etree import ElementTree


path = 'data3.xml'
tree = ElementTree.parse(path)
root = tree.getroot()
countries = root.findall('country')
for country in countries:
    gdppc = country.find('gdppc')
    print(country.attrib)
    print(gdppc.text)
{'name': 'Liechtenstein'}
141100
{'name': 'Singapore'}
59900
{'name': 'Panama'}
13600

孫ノードまで取得

for文をネストする。

cnt = 1
for child in root:
    print('---', cnt, '---')
    print(child.tag, child.attrib, child.text)
    for gild in child:
        print(gild.tag, gild.attrib, gild.text)
    cnt += 1
--- 1 ---
country {'name': 'Liechtenstein'}

rank {} 1
year {} 2008
gdppc {} 141100
neighbor {'name': 'Austria', 'direction': 'E'} None
neighbor {'name': 'Switzerland', 'direction': 'W'} None
--- 2 ---
country {'name': 'Singapore'}

rank {} 4
year {} 2011
gdppc {} 59900
neighbor {'name': 'Malaysia', 'direction': 'N'} None
--- 3 ---
country {'name': 'Panama'}

rank {} 68
year {} 2011
gdppc {} 13600
neighbor {'name': 'Costa Rica', 'direction': 'W'} None
neighbor {'name': 'Colombia', 'direction': 'E'} None

参考URL

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