使用ElementTree获取python3中的所有xml属性值
我有以下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 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']