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

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)

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

it2011 回答:如何在XML标记中提取值-python 3

使用lxml进行操作非常简单:

from lxml import etree
tree = etree.parse("country_data.xml")
tree.xpath('//year/text()')

输出:

  

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

,

您可以为此使用BeatifulSoup。

from bs4 import BeautifulSoup

years = []

with open('country_data.xml') as fp:
    soup = BeautifulSoup(fp,'lxml')

    for country in soup.findAll('country'):
        years_data = country.find('year')
        years.append(years_data.contents[0])

print('Years: {}'.format(years))

输出:

Years: ['2008','2011','2011']
本文链接:https://www.f2er.com/3156612.html

大家都在问