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