Python lxml and parsing a subtree
Question: I've got a xml which looks like this:

    
    
    <root>
    <foo>
    <a></a>
    <b></b>
    <c></c>
    </foo>
    <bars>
    <bar>
    <one>interesting</one>
    <two>interesting</two>
    <three>interesting</three>
    </bar>
    <bar>
    <one>interesting</one>
    <two>interesting</two>
    <three>interesting</three>
    </bar>
    <bar>
    <one>interesting</one>
    <two>interesting</two>
    <three>interesting</three>
    </bar>
    </bars>
    <root>
    

I want to extract the interesting text from all the bars. Can you tell me how
to start? I've tried to use

    
    
    bars = etree.iterparse(xml_data, tag="bars")
    

but I couldn't iterate through it.


Answer: Use `findall` method to return all matching elements.

    
    
    xml_data = '''<?xml version='1.0' encoding='ASCII' ?>
    <root>
    <foo>
    <a></a>
    <b></b>
    <c></c>
    </foo>
    <bars>
    <bar>
    <one>interesting</one>
    <two>interesting</two>
    <three>interesting</three>
    </bar>
    <bar>
    <one>interesting</one>
    <two>interesting</two>
    <three>interesting</three>
    </bar>
    <bar>
    <one>interesting</one>
    <two>interesting</two>
    <three>interesting</three>
    </bar>
    </bars>
    </root>
    '''
    
    from lxml import etree
    
    root = etree.fromstring(xml_data)
    for bars in root.findall('.//bars'):
        print(etree.tostring(bars, method='text'))
    

