2012-11-19 54 views
1

我使用ElementTree findall()來查找XML中具有特定標記的元素。我想把結果變成一個列表。此刻,我遍歷元素,爲每個元素挑選.text,並追加到列表中。我確信有一個更優雅的方式來做到這一點。將ElementTree的findall()轉換爲列表

#!/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'] 

回答

1

你可以試試這個 - 它採用了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 = []定義 - 如果找不到匹配的元素,結果將只是一個空列表。

+0

非常優雅,謝謝! –

+0

@jhonan沒問題,希望它有幫助! – RocketDonkey