【发布时间】:2019-11-05 20:23:27
【问题描述】:
下面是一个示例 XML 文件,我想解析并获取年份标签之间的值(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)
但是当我尝试该代码时,没有任何打印。有什么想法/建议吗?
【问题讨论】:
-
尝试打印(year.text)
-
我可以给你发消息来帮助我吗
标签: python-3.x xml elementtree xml.etree