Reputation: 45
I thought this would work for searching for tag values of "error"
import xml.etree.cElementTree as ET
xml = """
<tag1>
<tag2>
error
</tag2>
<tag3>
working
</tag3>
<tag4>
<tag5>
error
</tag5>
</tag4>
</tag1>
"""
for event, element in ET.fromstring(xml):
if element.text.strip() == "error":
print element.tag
I run in to the following error:
Traceback (most recent call last):
File "test.py", line 19, in <module>
for event, element in ET.fromstring(xml):
ValueError: need more than 0 values to unpack
What does "need more than 0 values to unpack" mean?
Upvotes: 2
Views: 257
Reputation: 77407
The document iterator returns Element, which can't be split into (event, element). You should remove 'event'. But that's not quite right either because the element iterator will only give you children (tag2, tag3, tag4). You need to call element.iter() to get all descendents.
>>> for element in ET.fromstring(xml).iter():
... if element.text.strip() == 'error':
... print element.tag
...
tag2
tag5
>>>
Upvotes: 1
Reputation: 1124718
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
Upvotes: 3