使用xml.etree.ElementTree搜索XML元素树的属性

时间:2014-08-26 20:46:25

标签: python xml parsing elementtree

我将使用Python的ElementTree文档here中的示例:

<?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>

有没有办法搜索属性并返回属性匹配的元素?在上面的例子中,我想搜索属性名称为Singapore的元素。 findall()功能只按标签名称搜索,即“国家/地区”,“排名”等。我知道我可以循环浏览所有国家/地区标签,看看他们的名称属性是否与新加坡匹配,但我想知道是否有使用我缺少的内置函数的更快方法。

1 个答案:

答案 0 :(得分:3)

使用XPath表达式(如正则表达式,但对于XML)

类似于上面的例子:

# Nodes with name='Singapore' that have a 'year' child
root.findall(".//year/..[@name='Singapore']")
相关问题