python - 有没有办法直接在xml中获取属性文本,而不需要遍历python中elementree中的子元素

标签 python xml elementtree

我正在使用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/

相关文章:

Python3 - 尝试获取数据属性值时,XPath 查询不会从站点返回整个列表

python - 从 3 个文本文件输出匹配行以及匹配行下的行

python - 使用 Python 的 unittest 模块作为测试运行器时,如何在测试前运行初始化代码?

python - 是否应该只在 except block 内调用 logger.exception?为什么?

python - pandasrolling如何保留每个时间窗口的第一个时间索引

java - 如何将xml绑定(bind)到bean

python - 在 Python 的 ElementTree 中提取标签后的文本

sql - 获取 sql 列使用的 XML 模式

c# - XML反序列化C#数组

python - 有没有办法从 ElementTree 元素中获取行号