如何在ElementTree中使用xpath搜寻多个属性

问题描述 投票:-1回答:2

我正在寻找从XML文件(https://digitallibrary.un.org/search?ln=en&p=A/RES/72/266&f=&rm=&ln=en&sf=&so=d&rg=50&c=United+Nations+Digital+Library+System&of=xm&fti=0&fti=0)中隔离以下值。

<collection>
  <record>
    ...
    <datafield tag="993" ind1="2" ind2=" ">
      <subfield code="a">A/C.5/72/L.22</subfield> # Value to isolate: A/C.5/72/L.22
    </datafield>
    <datafield tag="993" ind1="3" ind2=" ">
      <subfield code="a">A/72/682</subfield> # Value to isolate: A/72/682
    </datafield>
    <datafield tag="993" ind1="4" ind2=" ">
      <subfield code="a">A/72/PV.76</subfield> # Value to isolate: A/72/PV.76
    </datafield>
    ...
  </record>
  <record>
    ...
    <datafield tag="993" ind1="2" ind2=" ">
      <subfield code="a">A/C.5/72/L.22</subfield> # Value to isolate: A/C.5/72/L.22
    </datafield>
    <datafield tag="993" ind1="3" ind2=" ">
      <subfield code="a">A/72/682</subfield> # Value to isolate: A/72/682
    </datafield>
  </record>
  ...
</collection>

我准备的代码似乎只能为每个记录标识带有标签993的第一项。

for record in root:
  if record.find("{http://www.loc.gov/MARC21/slim}datafield[@tag='993']/{http://www.loc.gov/MARC21/slim}subfield[@code='a']") is not None:
    symbol = record.find("{http://www.loc.gov/MARC21/slim}datafield[@tag='993']/{http://www.loc.gov/MARC21/slim}subfield[@code='a']").text
    print symbol

是否有一种方法可以循环使用ElementTree的xpath搜索多个属性?预先谢谢你。

python xpath elementtree
2个回答
0
投票

docs显示.find()仅获得第一个匹配的子元素。听起来像您想要的.findall()

以下内容似乎对我有用:

import xml.etree.ElementTree as ET
tree = ET.parse(input_file)
root = tree.getroot()

for record in root:
    xpath = "{http://www.loc.gov/MARC21/slim}datafield[@tag='993']/{http://www.loc.gov/MARC21/slim}subfield[@code='a']"
    if record.findall(xpath) is not None:
        for symbol in record.findall(xpath):
            print symbol.text


0
投票

要完成user3091877的回答,请使用备用XPath选项:

//*[name()="subfield"][@code="a"][parent::*[@tag="993"]]/text()

编辑:这将返回6个值(@ tag = 993和@ ind1 = 3):

//*[name()="subfield"][parent::*[@tag="993" and @ind1="3"]]/text()
© www.soinside.com 2019 - 2024. All rights reserved.