如何在XML标记-python 3中提取值

问题描述 投票:1回答:2

Nelow是一个示例XML文件,我想对其进行解析并获取year标记之间的值(2008年)

<?xml version="1.0"?>
<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>

有没有办法提取年份标记(2008.2011等)之间的数据并使用python打印出来?

这里是到目前为止的代码:

import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()

for year in root.iter('year'):
   print(year.attrib)

但是当我尝试该代码时,什么也不会打印。有任何想法/建议吗?

python-3.x xml elementtree xml.etree
2个回答
0
投票
输出:

[''2008','2011','2011']

0
投票
输出:

['2008', '2011', '2011']

© www.soinside.com 2019 - 2024. All rights reserved.