Skip to main content
 首页 » 编程设计

python之将 ElementTree findall() 转换为列表

2025年05月04日10jiqing9006

我正在使用 ElementTree findall() 在我的 XML 中查找具有特定标记的元素。我想把结果变成一个列表。目前,我正在遍历元素,为每个元素挑选出 .text,并将其附加到列表中。我确信有一种更优雅的方法可以做到这一点。

#!/usr/bin/python2.7 
# 
from xml.etree import ElementTree 
import os 
myXML = '''<root> 
<project project_name="my_big_project"> 
<event name="my_first_event"> 
<location>London</location> 
<location>Dublin</location> 
<location>New York</location> 
<month>January</month> 
<year>2013</year> 
</event> 
</project> 
</root> 
''' 
 
tree = ElementTree.fromstring(myXML) 
for node in tree.findall('.//project'): 
  for element in node.findall('event'): 
    event_name=element.attrib.get('name') 
    print event_name 
    locations = [] 
    if element.find('location') is not None: 
      for events in element.findall('location'): 
        locations.append(events.text) 
# Could I use something like this instead? 
#      locations.append(''.join.text(*events) for events in element.findall('location')) 
 
print locations 

输出这个(这是正确的,但我想将 findall() 结果直接分配给一个列表,如果可能的话,以文本格式;

my_first_event 
['London', 'Dublin', 'New York'] 

请您参考如下方法:

你可以试试这个 - 它使用 list comprehension生成列表,而无需创建空白列表然后追加。

if element.find('location') is not None: 
  locations = [events.text for events in element.findall('location')] 

有了这个,你也可以摆脱上面的 locations 定义,所以你的代码将是:

tree = ElementTree.fromstring(myXML) 
for node in tree.findall('.//project'): 
  for element in node.findall('event'): 
    event_name=element.attrib.get('name') 
    print event_name 
    if element.find('location') is not None: 
      locations = [events.text for events in element.findall('location')] 
 
print locations 

你需要警惕的一件事是你对位置所做的事情 - 如果 location 不存在,它就不会被定义,所以你会得到一个 NameError 如果您尝试打印它但它不存在。如果这是一个问题,您可以保留 locations = [] 定义 - 如果找不到匹配的元素,结果将只是一个空列表。