title: Getting subelements using lxml and iterparse
body: <p>I am trying to write a parsing algorithm to efficiently pull data from an xml document. I am currently rolling through the document based on elements and children, but would like to use iterparse instead. One issue is that I have a list of elements that when found, I want to pull the child data from them, but it seems like using iterparse my options are to filter based on either one element name, or get every single element.</p>
  
  <p>Example xml:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;data_object xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt;
   &lt;source id="0"&gt;
    &lt;name&gt;Office Issues&lt;/name&gt;
    &lt;datetime&gt;2012-01-13T16:09:15&lt;/datetime&gt;
    &lt;data_id&gt;7&lt;/data_id&gt;
   &lt;/source&gt;
   &lt;event id="125"&gt;
    &lt;date&gt;2012-11-06&lt;/date&gt;
    &lt;state_id&gt;7&lt;/state_id&gt;
   &lt;/event&gt;
   &lt;state id="7"&gt;
    &lt;name&gt;Washington&lt;/name&gt;
   &lt;/state&gt;
   &lt;locality id="2"&gt;
    &lt;name&gt;Olympia&lt;/name&gt;
    &lt;state_id&gt;7&lt;/state_id&gt;
    &lt;type&gt;City&lt;/type&gt;
   &lt;/locality&gt;
   &lt;locality id="3"&gt;
    &lt;name&gt;Town&lt;/name&gt;
    &lt;state_id&gt;7&lt;/state_id&gt;
    &lt;type&gt;Town&lt;/type&gt;
   &lt;/locality&gt;
  &lt;/data_object&gt;
  </code></pre>
  
  <p>Code example:</p>
  
  <pre><code>from lxml import etree
  
  fname = "test.xml"
  ELEMENT_LIST = ["source", "event", "state", "locality"]
  
  with open(fname) as xml_doc:
      context = etree.iterparse(xml_doc, events=("start", "end"))
  
      context = iter(context)
  
      event, root = context.next()
  
      base = False
      b_name = ""
  
      for event, elem in context:
          if event == "start" and elem.tag in ELEMENT_LIST:
              base = True
              bname = elem.tag
              children = elem.getchildren()
              child_list = []
              for child in children:
                  child_list.append(child.tag)
              print bname + ":" + str(child_list)
          elif event == "end" and elem.tag in ELEMENT_LIST:
              base = False
              root.clear()
  </code></pre>