4

I have a problem with ElementTree.iter().

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

So here's what I've 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 error AttributeError: ElementTree instance has no attribute 'iter'

Additional info: The version of my Python is 2.4 I separately installed elementtree. Other examples in the link that I provide is working in my Python installed. Only the ElementTree.iter() is not working. Thanks in advance for all of your help. Cheers!

4

3 回答 3

20

In your case, you should replace the .iter() by .getiterator(), and you possibly should call it for the root element, not for the tree (but I am not sure because I do not have the Python 2.4 and the module at my 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 the older functionality that was deprecated in Python 2.7. For Python 2.7, the .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

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

于 2012-07-09T07:44:20.440 回答
1

Try to use findall instead of iter. ElementTree's iter() equivalent in Python2.6

于 2012-07-09T07:29:29.893 回答
0

According to python document this API should be in 2.5, however it doesn't exist. You can use the below mentioned code 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
于 2012-07-09T07:50:08.613 回答