我正在尝试使用Python迭代XML文件。这是一段代码:
for fields in root.iter('context'):
for ID in fields.iter('ID'):
try:
name = ID.attrib['name']
if name in fields_to_remove:
removed.append({'name': name, 'tag': ID})
except KeyError:
pass
if removed:
comment = ','.join([ ID['name'] for ID in removed])
for ID in removed:
fields.remove(ID['tag'])
fields.append(ET.Comment('Removed ' + comment))
removed = []
XML示例:
<context name="Subscription" category="subscription" type="generic" optimizeSize="1">
<field name="DELTA_MID_RT" type="bool" id="-1" defaultValue="false"/>
<field name="API::TZO" type="int32" id="-1" defaultValue="0"/>
<field name="API::DIVIDENTADJUST" type="bool" id="-1"/>
</context>
错误讯息:
Traceback (most recent call last):
File "parser.py", line 20, in <module>
for fields in root.iter('context'):
AttributeError: _ElementInterface instance has no attribute 'iter'