我正在使用python模块:xml.etree.ElementTree
来解析xml文件。
我很好奇是否有一种方法可以直接找到嵌套很深的属性。
例如,如果我想获取 neigbhor 的 name 属性
(如果存在),
如果我的根是data
,我需要遍历country/rank/year/gdppc
。有没有快速查找该属性的方法?
<data>
<country name="Liechtenstein">
<rank>
<year>
<gdppc>
<neighbor name="Austria" direction="E"/>
</gdppc>
</year>
</rank>
</country>
</data>
编辑:
我在这条线上尝试过一些东西。但没有帮助;我不确定是否应该使用 resp.content
来获取 xml
resp=requests.get(url_fetch,params=query)
with open(resp.content) as fd:
doc = ElementTree.parse(fd)
name = doc.find('PubmedArticle//Volume').text
print name
这是xml:
最佳答案
根据您的数据的外观以及您想要完成的具体任务,您可以执行以下操作:
with open('data.xml') as fd:
doc = ElementTree.parse(fd)
name = doc.find('country[@name="Liechtenstein"]//neighbor').get('name')
print name
给定上面的输入将产生:
Austria
如果您使用 Python 解析 XML,您可能需要查看 lxml
模块,它完全支持 XPath 查询。
这对我来说适用于您上面提供的 URL:
#!/usr/bin/python
import requests
from xml.etree import ElementTree
res = requests.get('http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=24059499&retmode=xml')
doc = ElementTree.fromstring(res.content)
ele = doc.find('.//PubmedArticle//Volume')
print ele.text
关于python - 有没有办法直接在xml中获取属性文本,而不需要遍历python中elementree中的子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21345384/