ElementTree's iter() equivalent in Python2.6

本小妞迷上赌 提交于 2019-12-03 23:43:41

问题


I have this code with ElementTree that works well with Python 2.7. I needed to get all the nodes with the name "A" under "X/Y" node.

from xml.etree.ElementTree import ElementTree

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

However, when I tried to run it with Python 2.6, I got this error.

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

It looks like that Python 2.6 ElementTree's node doesn't have the iter(). How can I implement the iter() with Python 2.6?


回答1:


Note that iter is available in Python 2.6 (and even 2.5 - otherwise, there'd be a notice in the docs), so you don't really need a replacement.

You can, however, use findall:

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



回答2:


Not sure if this is what you are looking for, as iter() appears to be around in 2.6, but there's getiterator()

http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.getiterator



来源:https://stackoverflow.com/questions/7616800/elementtrees-iter-equivalent-in-python2-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!