Search code examples
pythonxmlelementtreecelementtree

Python search data within XML elements


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?


Solution

  • 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