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>
Spécifiez la balise souhaitée avec find ou findall Obtenez toutes les balises de pays ci-dessous
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
Nest pour les déclarations.
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
https://docs.python.org/ja/3/library/xml.etree.elementtree.html
Recommended Posts