【问题标题】:How to extract values inside an XML tag-python 3如何在 XML 标签中提取值-python 3
【发布时间】: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


【解决方案1】:

使用 lxml 很简单:

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

输出:

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

【讨论】:

  • 我能快速给你发消息吗
【解决方案2】:

您可以为此使用 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']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 2013-04-08
    • 2016-06-10
    • 2014-09-27
    • 2021-05-06
    • 1970-01-01
    • 2021-10-21
    相关资源
    最近更新 更多