parsing xml with python, selecting a tag using a sibling tag as selector
Question: from the following xml structure and using ElementTree i'm trying to parse the
descriptions' text _solely_ for the items where titles' text contain a certain
keyword of interest. thanks for any suggestion

    
    
    <data>
      <item>
          <title>contains KEYWORD of interest </title>
          <description> description text of interest "1"</description>
      </item>
      <item>
          <title>title text </title>
          <description> description text not of interest</description>
      </item>
      .
      .
      .
      <item>
          <title>also contains KEYWORD of interest </title>
          <description> description text of interest "k" </description>
      </item>
    </data>
    

desired outcome:

description text of interest "1"

description text of interest "k"


Answer: You can use [`lxml`](http://lxml.de/) which support
[XPath](http://lxml.de/xpathxslt.html):

    
    
    xml = '''<data>
      <item>
          <title>contains KEYWORD of interest </title>
          <description> description text of interest "1"</description>
      </item>
      <item>
          <title>title text </title>
          <description> description text not of interest</description>
      </item>
      .
      .
      .
      <item>
          <title>also contains KEYWORD of interest </title>
          <description> description text of interest "k" </description>
      </item>
    </data>
    '''
    
    import lxml.etree
    root = lxml.etree.fromstring(xml)
    root.xpath('.//title[contains(text(), "KEYWORD")]/'
               'following-sibling::description/text()')
    # => [' description text of interest "1"', ' description text of interest "k" ']
    

Using
[`xml.etree.ElementTree`](https://docs.python.org/2/library/xml.etree.elementtree.html):

    
    
    import xml.etree.ElementTree as ET                                             
    root = ET.fromstring(xml)
    [item.find('description').text for item in root.iter('item')
     if'KEYWORD' in item.find('title').text]
    # => [' description text of interest "1"', ' description text of interest "k" ']
    

