![](/img/trans.png)
[英]Get XML Parent ID and all Childs underneath using ElementTree and python
[英]Get all xml attribute values in python3 using ElementTree
我有以下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>
我想使用ElementTree编写python 3代码来获取所有国家/地区名称。 所以最终的结果应该是dict
或array
[ '列支敦士登', '新加坡', '巴拿马']
我试图使用Xpath做到这一点,但无处可去。 所以我的代码如下
import xml.etree.ElementTree as ET
tree = ET.parse(xmlfile)
root = tree.getroot()
names = root.findall("./country/@name")
但是上面的方法不起作用,因为我认为我的xpath是错误的。
使用findall()
获取所有country
标记并从.attrib
字典中获取name
属性:
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')])
打印['Liechtenstein', 'Singapore', 'Panama']
。
请注意,您无法使用xpath表达式//country/@name
获取属性值,因为xml.etree.ElementTree
仅提供有限的Xpath支持 。
仅供参考, lxml
提供了更完整的xpath支持,因此可以更轻松地获取属性值:
from lxml import etree as ET
data = """your xml here"""
tree = ET.fromstring(data)
print(tree.xpath('//country/@name'))
打印['Liechtenstein', 'Singapore', 'Panama']
。
你可以用
import xml.etree.ElementTree as ET
xml=ET.fromstring(contents)
xml.find('./element').attrib['key']
谢这里来源
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.