繁体   English   中英

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

[英]Get all xml attribute values in python3 using ElementTree

我有以下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>

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

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

我试图使用Xpath做到这一点,但无处可去。 所以我的代码如下

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

names = root.findall("./country/@name")

但是上面的方法不起作用,因为我认为我的xpath是错误的。

使用findall()获取所有country标记并从.attrib字典中获取name属性:

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')])

打印['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'))

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

你可以用

 import xml.etree.ElementTree as ET

 xml=ET.fromstring(contents)



xml.find('./element').attrib['key']

这里来源

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM