如何在python中搜索具有给定属性值的Xml节点 [英] How to search for a Xml node with a given attribute value in python

查看:32
本文介绍了如何在python中搜索具有给定属性值的Xml节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 XML 文件,我想获取名称中包含in"模式的国家/地区节点.

I have this XML file and I want to get the country nodes which have the pattern 'in' in their name.

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

我已经试过了

    import xml.etree.ElementTree as ET
    tree = ET.parse('test.xml')
    root = tree.getroot()
    list=root.find(".//country[contains(@name, 'Pana')]")

但我收到一个错误:语法错误:谓词无效

But I am getting an error : SyntaxError: invalid predicate

有人可以帮忙解决这个问题吗?

Could anyone please help how to solve this?

推荐答案

xml.etree.ElementTree 仅提供对用于定位树中元素的 XPath 表达式的有限支持,并且不包括 xpath contains() 函数.有关支持的列表,请参阅文档xpath 语法.

xml.etree.ElementTree provides only limited support for XPath expressions for locating elements in a tree, and that doesn't include xpath contains() function. See the documentation for list of supported xpath syntax.

您需要求助于提供更好 xpath 支持的库,例如 lxml,或使用更简单的 xpath并手动进行进一步过滤,例如:

You need to resort to a library that provide better xpath support, like lxml, or use simpler xpath and do further filtering manually, for example :

import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()
list = filter(lambda x: 'Pana' in x.get('name'), root.findall(".//country[@name]"))

这篇关于如何在python中搜索具有给定属性值的Xml节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆