Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用ElementTree获取python3中的所有xml属性值_Python_Xml_Python 3.x_Elementtree - Fatal编程技术网

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

使用ElementTree获取python3中的所有xml属性值,python,xml,python-3.x,elementtree,Python,Xml,Python 3.x,Elementtree,我有以下xml文件 <?xml version="1.0"?> <data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year>2008</year> <gdppc>141100</gdppc> <neighbor name="Au

我有以下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>
但是,上述方法不起作用,因为我觉得我的xpath是错误的

用于获取所有
国家
标记,并从字典中获取
名称
属性:

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')])
打印
[‘列支敦士登’、‘新加坡’、‘巴拿马’]

请注意,您无法使用xpath表达式
//country/@name
获取属性值,因为
xml.etree.ElementTree
仅提供


仅供参考,提供了更完整的xpath支持,因此更容易获取属性值:

from lxml import etree as ET

data = """your xml here"""

tree = ET.fromstring(data)
print(tree.xpath('//country/@name'))
打印您可以使用的

 import xml.etree.ElementTree as ET

 xml=ET.fromstring(contents)



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

检查来源

谢谢。有没有可能把所有的名字都放在一行的数组里。我想出来了。谢谢。@VinayJoseph我还添加了一个
lxml
选项-以防您可以使用第三方模块。还添加了文档的链接。
 import xml.etree.ElementTree as ET

 xml=ET.fromstring(contents)



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