XML processing in Python with ElementTree

I have a problem with ElementTree.iter ().

So, I tried this example at this link: http://eli.thegreenplace.net/2012/03/15/processing-xml-in-python-with-elementtree/

So here is what I tried:

import elementtree.ElementTree as ET tree = ET.parse('XML_file.xml') root = tree.getroot() for elem in tree.iter(): print elem.tag, elem.attrib 

And I get this AttributeError error: the ElementTree instance does not have the attribute 'iter'

Additional Information: My Python version is 2.4. I installed elementtree separately. Other examples in the link I provide work on my Python. Only ElementTree.iter () does not work. Thank you in advance for your help. Hooray!

+4
source share
3 answers

In your case, you should replace .iter() with .getiterator() , and you should probably call it for the root element, not the tree (but I'm not sure, because I don't have Python 2.4 and I have a module in hands).

 import elementtree.ElementTree as ET tree = ET.parse('XML_file.xml') root = tree.getroot() for elem in root.getiterator(): print elem.tag, elem.attrib 

This is older functionality, deprecated in Python 2.7. For Python 2.7, .iter() should work with the built-in module:

 import xml.etree.ElementTree as ET tree = ET.parse('XML_file.xml') root = tree.getroot() for elem in root.iter(): print elem.tag, elem.attrib 

Note: the standard module also supports direct iteration through the node element (i.e. no .iter() or any other method, only for elem in root: . It differs from .iter() - it goes only through the nodes of the immediate descendant. Similar functionality is implemented in older versions as .getchildren() .

+20
source

Try using findall instead of iter. equivalent of iter () ElementTree in Python2.6

+1
source

According to the python document, this API should be in 2.5, however it does not exist. You can use the code below for iteration. This way you can also pass the tag.

 def iter(element, tag=None): if tag == "*": tag = None if tag is None or element.tag == tag: yield element for e in element._children: for e in e.iter(tag): yield e 
0
source

All Articles