Iterating over a Element
object yields just one element at a time, but your loop is expecting two values. You are confusing .fromstring()
with .iterparse()
here.
You really just need .findall()
:
tree = ET.fromstring(xml)
for elem in tree.findall('.//*'):
if elem.text and elem.text.strip() == 'error':
print elem.tag
or .iter()
, which does the same (loop over all elements in the tree):
tree = ET.fromstring(xml)
for elem in tree.iter():
if elem.text and elem.text.strip() == 'error':
print elem.tag
If you really wanted to use the event-driver iterparse
you'd need to provide a file object:
from cStringIO import StringIO
for event, element in ET.iterparse(StringIO(xml)):
if element.text.strip() == "error":
print element.tag
All snippets print:
tag2
tag5