【问题标题】:Python searching for particular child of childPython搜索孩子的特定孩子
【发布时间】:2018-10-01 14:26:29
【问题描述】:

我正在尝试下载 xml 数据(我已经完成)解析它(我已经完成)并搜索 xml 数据以返回结果。

<Substances>
<Name>Substance 1</Name>
<Product>
<Product_name>Product ABC</Product_name>
<MRL>0.0123*</MRL>
</Product>
<Product>
<Product_name>Product XYZ</Product_name>
<MRL>0.0234*</MRL>
</Product>
</Substances>
<Substances>
<Name>Substance 2</Name>
<Product>
<Product_name>Product ABC</Product_name>
<MRL>0.789*</MRL>
</Product>
<Product>
<Product_name>Product XYZ</Product_name>
<MRL>0.567</MRL>
</Product>
</Substances>

在本地保存 xml 文件后(因为它很大),我想搜索一种物质,比如“物质 2”,然后搜索产品名称“产品 XYZ”,然后搜索 MRL 数据在该物质特有的产品下。

(注意,物质都是唯一的,但产品不是,因为产品在每种不同的物质下都有重复)

为了更清楚,我举个例子:如果物质搜索词是“物质 2”,产品搜索词是“产品 XYZ”,程序将返回“0.567”。

[编辑] 到目前为止,我与这个问题相关的部分代码是:

substance='Substance 2'
product_name='Product XYZ'

for mrl in root.findall(substance):
    for prod in find(product):
        print(mrl.text)

这不会引发错误,但也不会打印任何输出。

[\编辑]

如果需要更多详细信息,请告诉我。帮助表示赞赏。

【问题讨论】:

  • 你的代码在哪里?你试过什么没用?我们都很乐意提供帮助,但您必须首先表现出真正的努力来解决问题......
  • @brunodesthuilliers 我将编辑问题以添加我的代码(这不起作用)

标签: python xml parsing search


【解决方案1】:

使用本教程https://docs.python.org/3/library/xml.etree.elementtree.html

for substance in root.find('Substances')
  if substance.find("Name").text = "Substance 2":
    for product in substance.findall('Product'):
        if  product.find('Product_name').text == 'Product XYZ':
            return product.find('MRL').text

【讨论】:

  • 我的代码现在是:code for s in root.findall('Substances'): if s.find("Name").text==substance: for p in s.findall( 'Product'): if p.find('Product_name').text ==product: mrl=p.find('MRL').text print ('MRL of ',substance,' for ',product,' is' ,mrl) code 效果很好。谢谢!
猜你喜欢
  • 2023-02-25
  • 1970-01-01
  • 2019-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多