Processing XML in Python with ElementTree

匿名 (未验证) 提交于 2019-12-03 08:48:34

问题:

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!

回答1:

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



回答2:

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



回答3:

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 


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