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']
非常優雅,謝謝! –
@jhonan沒問題,希望它有幫助! – RocketDonkey