这两个函数使用的场景有所差异: Element.iter()用来寻找所有符合要求的Tag,注意,这里查找的范围是所有孩子和孩子的孩子 and so on。如果查看所有的year,可以使用下面的代码:
for neighbor in root.iter('year'): print neighbor.text 返回
2008
2011
2011
Element.findall()只查找直接的孩子,返回所有符合要求的Tag的Element,而Element.find()只返回符合要求的第一个Element。如果查看Singapore的year的值,可以使用下面的代码:
for country in root.findall('country'): if country.attrib['name'] == 'Singapore':
year = country.find('year') # 使用Element.find()
print year.text
for country in root.findall('country'): if country.attrib['name'] == 'Singapore':
years = country.findall('year') # 使用Element.findall()
五、XPath支持
XPath表达式用来在XML中定位Element,下面给一个例子来说明:
import xml.etree.ElementTree as ET
root = ET.fromstring(countrydata)# Top-level elementsroot.findall(".")# All 'neighbor' grand-children of 'country' children of the top-level# elementsroot.findall("./country/neighbor")# Nodes with name='Singapore' that have a 'year' childroot.findall(".//year/..[@name='Singapore']")# 'year' nodes that are children of nodes with name='Singapore'root.findall(".//*[@name='Singapore']/year")# All 'neighbor' nodes that are the second child of their parentroot.findall(".//neighbor[2]") 参考
ElementTree主页
ElementTree的函数与类介绍
Written by chenzq.
2014/5/30