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

马丁

我将使用从Python的ElementTree文档的例子在这里

<?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()功能仅按标签名称进行搜索,即“国家”,“等级”等。我知道我可以循环遍历所有国家标签,并查看它们的名称属性是否与新加坡匹配,但我想知道是否有一种更快的方法可以使用内置-在我所缺少的功能中。

约翰泰尔索尔

使用XPath表达式(类似于正则表达式,但用于XML)

与上面的示例类似:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

使用 Python xml.etree.ElementTree 遍历 XML 树的问题

来自分类Dev

使用xml.etree.ElementTree XML解析子元素

来自分类Dev

xml.etree.ElementTree getElementByID()?

来自分类Dev

xml.etree.ElementTree findall

来自分类Dev

xml.etree.ElementTree findall

来自分类Dev

使用Etree从XML中删除特定元素

来自分类Dev

使用python etree获取xml的属性

来自分类Dev

python xml.etree.ElementTree追加到子元素

来自分类Dev

使用xml.etree.ElementTree解析XML时获取空列表作为属性

来自分类Dev

xml.etree.ElementTree-麻烦设置xmlns ='...'

来自分类Dev

Python xml.etree.ElementTree 问题

来自分类Dev

使用 xmldom 或 etree 使用 python 解析 XML

来自分类Dev

xml.etree.ElementTree iterparse()仍在使用大量内存?

来自分类Dev

使用html5lib和xml.etree.ElementTree

来自分类Dev

如何使用xml.etree.ElementTree访问标签之间的文本

来自分类Dev

无法使用xml.etree.ElementTree解析html

来自分类Dev

如何使用xml.etree.ElementTree访问标签之间的文本

来自分类Dev

使用etree删除元素

来自分类Dev

使用Etree和Python编辑XML

来自分类Dev

在Python中使用etree解析XML

来自分类Dev

使用find方法(xml.etree.ElementTree)后获取父元素

来自分类Dev

如何使用xml.etree.ElementTree Python格式化属性,前缀和标签

来自分类Dev

etree xml解析和删除

来自分类Dev

Python xml.etree转义

来自分类Dev

Python xml.etree 问题

来自分类Dev

python(xml.etree.ElementTree)中的XML解析

来自分类Dev

查询:使用xml.etree解析以下xml代码?

来自分类Dev

使用Python和xml.etree解析XML

来自分类Dev

使用xml.etree.cElementTree用空格创建xml文档