16

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?

prosseek
  • 182,215
  • 215
  • 566
  • 871

2 Answers2

20

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

Adam Wagner
  • 15,469
  • 7
  • 52
  • 66
  • Thats what I was looking for. – skjoshi Jun 05 '15 at 02:00
  • Thanks for the info. So I have to explicitly switch to the deprecated getiterator() in order to maintain Python 2.6 compatibility. It kinda makes me think "so why did they deprecate the old function name in the first place?". – RayLuo Feb 02 '16 at 13:33
7

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('.//*')
phihag
  • 278,196
  • 72
  • 453
  • 469
  • It works fine, thanks. Is it OK just replace iter with findall? What would be the reason why iter() is introduced when we have finadll()? – prosseek Sep 30 '11 at 23:03
  • @prosseek `findall` is way more powerful than `iter`, and also potentially slower. Therefore, you should just use `iter` when you really want all nodes. In many cases, you want only a certain set of nodes, like `/group/product/price`. If that's the case, have a look at the documentation of `findall` - it might save you a lot of Python code. – phihag Oct 01 '11 at 09:09
  • 2
    Then what causes the error? I have the same problem: root.iter works in 2.7, raises the above error in 2.6. findall fixed it. – thumbtackthief May 30 '13 at 18:28
  • 7
    I don't see any iter() in python 2.6 http://docs.python.org/2.6/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.getiterator – shawn Jan 27 '14 at 20:06
  • I had similar trouble than OP when I wanted to get plain text of an element. Managed to put this together so I'll leave it here in case somebody needs it. `remove tags = lambda text: " ".join([i.text for i in xml.etree.ElementTree.fromstring(text).findall(".//*")])` – kecer Dec 25 '14 at 10:42