Have a look up to python documentation的所有子元素。它真的使用这个xml树作为例子。
import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()
country = root[0].getchildren()
map(lambda e: e.tag, r)
# ['rank', 'year', 'gdp', 'neighbor', 'neighbor']
顺便说一句,当你卡住了,打开repl,并一步一步走。我不记得以上所有的东西。最后2或3年前使用xml解析器。但我知道,“试试看”是最好的老师。
这些是步骤,我如何提出解决方案。
# imports and other stuff.
>>> tree = ET.parse('data.xml')
>>> root = tree.getroot()
>>> country = root[0]
>>> dir(country)
['__class__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__len__', '__module__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_children', 'append', 'attrib', 'clear', 'copy', 'extend', 'find', 'findall', 'findtext', 'get', 'getchildren', 'getiterator', 'insert', 'items', 'iter', 'iterfind', 'itertext', 'keys', 'makeelement', 'remove', 'set', 'tag', 'tail', 'text']
>>> country.keys()
['name']
>>> country.getchildren()
[<Element 'rank' at 0x7f873cf53910>, <Element 'year' at 0x7f873cf539d0>, <Element 'gdp' at 0x7f873cf53a90>, <Element 'neighbor' at 0x7f873cf53c10>, <Element 'neighbor' at 0x7f873cf53c50>]
>>> country.getchildren()[0]
<Element 'rank' at 0x7f873cf53910>
>>> r = country.getchildren()[0]
>>> dir(r)
['__class__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__len__', '__module__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_children', 'append', 'attrib', 'clear', 'copy', 'extend', 'find', 'findall', 'findtext', 'get', 'getchildren', 'getiterator', 'insert', 'items', 'iter', 'iterfind', 'itertext', 'keys', 'makeelement', 'remove', 'set', 'tag', 'tail', 'text']
>>> r.tag
'rank'
>>> r = country.getchildren()[0]
>>> r
<Element 'rank' at 0x7f873cf53910>
>>> r = country.getchildren()
>>> r
[<Element 'rank' at 0x7f873cf53910>, <Element 'year' at 0x7f873cf539d0>, <Element 'gdp' at 0x7f873cf53a90>, <Element 'neighbor' at 0x7f873cf53c10>, <Element 'neighbor' at 0x7f873cf53c50>]
>>> map(lambda e: e.tag, r)
['rank', 'year', 'gdp', 'neighbor', 'neighbor']
好测试,你尝试过什么? – amarnath