使用ElementTree在Python中处理XML [英] Processing XML in Python with ElementTree
问题描述
我对ElementTree.iter()有问题.
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/
这就是我尝试过的:
import elementtree.ElementTree as ET
tree = ET.parse('XML_file.xml')
root = tree.getroot()
for elem in tree.iter():
print elem.tag, elem.attrib
我得到这个错误AttributeError:ElementTree实例没有属性'iter'
And I get this error AttributeError: ElementTree instance has no attribute 'iter'
其他信息:我的Python版本是2.4我单独安装了elementtree.我提供的链接中的其他示例正在安装的Python中运行.仅ElementTree.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!
推荐答案
在您的情况下,应将.iter()
替换为.getiterator()
,并且可能应将其用于root
元素,而不是树(但是我不确定,因为我手头没有Python 2.4和模块).
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
这是Python 2.7中不推荐使用的较早功能.对于Python 2.7,.iter()
应该与内置模块一起使用:
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
注意事项:标准模块还支持通过元素节点的直接迭代(即,没有.iter()
或任何所谓的方法,仅是for elem in root:
).它不同于.iter()
-仅通过直接后代节点.在较早的版本中,实现了与.getchildren()
类似的功能.
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()
.
这篇关于使用ElementTree在Python中处理XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!