使用ElementTree获取python3中的所有xml属性值

Vin*_*eph 6 python xml elementtree python-3.x

我有以下xml文件

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>
Run Code Online (Sandbox Code Playgroud)

我想使用 ElementTree 编写 python 3 代码来获取所有国家/地区名称。所以最终结果应该是 a dictor arrayof

['列支敦士登'、'新加坡'、'巴拿马']

我正在尝试使用 Xpath 执行此操作,但一无所获。所以我的代码如下

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

names = root.findall("./country/@name")
Run Code Online (Sandbox Code Playgroud)

但是,以上不起作用,因为我觉得我的 xpath 是错误的。

ale*_*cxe 5

使用findall()得到所有的country标签,并获得name从属性.attrib词典:

import xml.etree.ElementTree as ET

data = """your xml here"""

tree = ET.fromstring(data) 
print([el.attrib.get('name') for el in tree.findall('.//country')])
Run Code Online (Sandbox Code Playgroud)

打印['Liechtenstein', 'Singapore', 'Panama']

请注意,您无法使用 xpath 表达式获取属性值,//country/@name因为xml.etree.ElementTree仅提供有限的 Xpath 支持


仅供参考,lxml提供了更完整的 xpath 支持,因此更容易获取属性值:

from lxml import etree as ET

data = """your xml here"""

tree = ET.fromstring(data)
print(tree.xpath('//country/@name'))
Run Code Online (Sandbox Code Playgroud)

打印['Liechtenstein', 'Singapore', 'Panama']