Python2.6中ElementTree的iter()等效项


问题内容

我有与ElementTree一起使用的代码,该代码与Python 2.7很好地兼容。我需要在“ X / Y”节点下获取所有名称为“ A”的节点。

from xml.etree.ElementTree import ElementTree

verboseNode = topNode.find("X/Y")
nodes = list(verboseNode.iter("A"))

但是,当我尝试使用Python 2.6运行它时,出现了此错误。

ionCalculateSkewConstraint.py", line 303, in getNodesWithAttribute
    nodes = list(startNode.iter(nodeName))
AttributeError: _ElementInterface instance has no attribute 'iter'

看起来Python 2.6 ElementTree的节点没有iter()。如何使用Python 2.6实现iter()?


问题答案:

请注意,该iter 功能 在Python 2.6(甚至2.5 )中
可用,否则docs中会有一个通知),因此您实际上不需要替换。

但是,您可以使用findall

def _iter_python26(node):
  return [node] + node.findall('.//*')