繁体   English   中英

Python ElementTree - 获取具有特定属性的元素

[英]Python ElementTree - getting element with specific attribute

我有一些 XML,其中每个元素的属性略有不同。 我只想拉取具有人口属性的元素。 下面的代码有效。 但是,如果我取消注释填充分配并在底部打印,它会失败,因为填充属性不在前两个元素中。 如何仅选择具有该特定属性的元素? 无论如何,这是我唯一需要的。

from xml.etree import ElementTree as ET

xml = '''<?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" population="500"/>
    </country>
</data>'''

root = ET.fromstring(xml)
print(root.tag)
print(root.findall('.//data/country'))

for target in root.findall('.//country'):
    name = target.attrib['name']
    #population = target.attrib['population']
    print(name)
    #print(population)

在代码中,您正在寻找具有population属性的country元素,但没有这样的元素。

要获取任何具有population属性的元素,您可以使用通配符作为元素名称:

for target in root.findall('.//*[@population]'):
    print(target.tag, target.attrib)

输出:

neighbor {'name': 'Colombia', 'direction': 'E', 'population': '500'}

暂无
暂无

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

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