要遍历所有节点,请在ElementTree而不是根Element上使用iter方法。
根是一个元素,就像树中的其他元素一样,并且实际上仅具有其自己的属性和子元素的上下文。ElementTree具有所有Elements的上下文。
例如,给定此xml
<?xml version="1.0"?><data> <country name="Liechtenstein"> <rank>1</rank> <year>2008</year> <gdppc>141100</gdppc> <neighbor name="Austria" direction="E"/> <neighbor name="Switzerland" direction="W"/> </country> <country name="Singapore"> <rank>4</rank> <year>2011</year> <gdppc>59900</gdppc> <neighbor name="Malaysia" direction="N"/> </country> <country name="Panama"> <rank>68</rank> <year>2011</year> <gdppc>13600</gdppc> <neighbor name="Costa Rica" direction="W"/> <neighbor name="Colombia" direction="E"/> </country></data>
您可以执行以下操作
>>> import xml.etree.ElementTree as ET>>> tree = ET.parse('test.xml')>>> for elem in tree.iter():... print elem... <Element 'data' at 0x10b2d7b50><Element 'country' at 0x10b2d7b90><Element 'rank' at 0x10b2d7bd0><Element 'year' at 0x10b2d7c50><Element 'gdppc' at 0x10b2d7d10><Element 'neighbor' at 0x10b2d7e90><Element 'neighbor' at 0x10b2d7ed0><Element 'country' at 0x10b2d7f10><Element 'rank' at 0x10b2d7f50><Element 'year' at 0x10b2d7f90><Element 'gdppc' at 0x10b2d7fd0><Element 'neighbor' at 0x10b2db050><Element 'country' at 0x10b2db090><Element 'rank' at 0x10b2db0d0><Element 'year' at 0x10b2db110><Element 'gdppc' at 0x10b2db150><Element 'neighbor' at 0x10b2db190><Element 'neighbor' at 0x10b2db1d0>


