使用python解析xml,使用同级标记作为选择器选择标记

使用python解析xml,使用同级标记作为选择器选择标记,python,xml,xml-parsing,Python,Xml,Xml Parsing,根据下面的xml结构,并使用ElementTree,我试图仅为标题文本包含特定关键字的项目解析描述文本。谢谢你的建议 <data> <item> <title>contains KEYWORD of interest </title> <description> description text of interest "1"</description> </item> <

根据下面的xml结构,并使用ElementTree,我试图仅为标题文本包含特定关键字的项目解析描述文本。谢谢你的建议

<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>

包含感兴趣的关键字
感兴趣的描述文本“1”
标题文本
不感兴趣的描述文本
.
.
.
还包含感兴趣的关键字
感兴趣的描述文本“k”
预期结果:

感兴趣的描述文本“1”

感兴趣的描述文本“k”

您可以使用以下支持:


谢谢@falsetru,它解决了问题。此外,出于学习目的,是否有关于ElementTree路径的建议?@Marius,就我所知,使用ElementTree,您需要更多步骤:查找
title
节点,按其文本进行筛选,查找兄弟
description
节点并检索其文本。@Marius,我添加了
ElementTree
版本。再次感谢@falsetru提供基于ElementTree的解决方案。
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" ']
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" ']