Processing XML in Python with ElementTree

半世苍凉 提交于 2019-12-05 11:49:32

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().

MartinM

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

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