0

给定以下xml:

<Title>
<EST>
  <EST_Start_Date>2009-09-21</EST_Start_Date>
  <EST_End_Date>2015-12-31</EST_End_Date>
  <EST_Version>
    <Vendor_ID>asdf-200130</Vendor_ID>
    <Master_Type_HD_SD>SD</Master_Type_HD_SD>
  </EST_Version>
  <EST_Version>
    <Digital_SKU>205119</Digital_SKU>
    <Vendor_ID>qwer-205119</Vendor_ID>
    <Master_Type_HD_SD>HD</Master_Type_HD_SD>
  </EST_Version>
</EST>
</Title>

和一个Title节点:

titles = node.xpath("//Title")
for title in titles:
    est=title.find('EST')
    hd_vendor_id = ?

在这种情况下,我将如何提取高清供应商 ID qwer-205118?lxml 调用应该与给定的 Title 节点相关,因为 xml 文档中有多个标题。

4

1 回答 1

3

使用 XPath 的强大功能!通过在 EST_Version 元素上使用谓词,您可以找到具有 HD-Master_Type 的谓词:

titles = node.xpath("//Title")
for title in titles:
    hd_vendor_id = title.xpath(
        "./EST/EST_Version[Master_Type_HD_SD='HD']/Vendor_ID)")

如果您只需要供应商 ID,则可以使用一个 XPath:

node.xpath("//Title/EST/EST_Version[Master_Type_HD_SD='HD']/Vendor_ID/text()")

如果您需要从每个 EST 元素中获得更多信息,您可以坚持使用您的语法:

titles = node.xpath("//Title")
for title in titles:
    est=title.find('EST')
    hd_vendor_id = est.xpath("./EST_Version[Master_Type_HD_SD='HD']/Vendor_ID)"

或者,例如,使用 XPath 立即选择 EST 元素:

ests = node.xpath("//Title/EST")
for est in ests:
    hd_vendor_id = est.xpath("./EST_Version[Master_Type_HD_SD='HD']/Vendor_ID)"
于 2012-06-30T00:54:43.920 回答