Python search data within all XML elements
Question: Newbie - I am trying to use lxml to find "error" in any element (sample XML
file below, but it should work regardless to how nested the tags are):

    
    
    <test>
      <test1>
        error
      </test1>
      <test2>  
        <test3>
          error
        </test3>
      </test2>
    </test>
    

So far it seems that lxml is only capable of searching for tags and not the
data within the tags - is this correct?


Answer: Are you asking if there's a built-in function to search the text in an
element? It's pretty simple to write your own search routine using `lxml`'s
`etree` parser. For example:

**test.xml**

    
    
    <test>
      <test1>
        error
      </test1>
      <test2>  
        <test3>
          error
        </test3>
      </test2>
    </test>
    

And from the command line:

    
    
    >>> import lxml.etree as etree
    >>> for event, element in etree.iterparse("test.xml"):
    ...   # Print the tag of a matching element
    ...   if element.text.strip() == "error":
    ...     print element.tag
    ... 
    test1
    test3
    

EDIT: If you end up going this route and don't need to muck about with XML
namespaces I recommend you check out `xml.etree.cElementTree` instead of
`lxml.etree`. It's included in the Python standard modules and is on par or
slightly faster than `lxml.etree`.

