首页 > 解决方案 > 使用 xpath 通过属性 ID 和文本查找节点

问题描述

我了解如何通过属性 ID 或文本查找节点,但不确定两者的语法。我正在使用 XML 库,我无权访问,lxml因为无法将它安装在我的工作计算机上。这是我正在使用的 XML 的摘录。

<product product-id="000100015BA00-00823">
    <ean/>
    <upc/>
    <page-attributes/>
    <custom-attributes>
        <custom-attribute attribute-id="color">000100015BA00-00823</custom-attribute>
    </custom-attributes>
    <pinterest-enabled-flag>false</pinterest-enabled-flag>
    <facebook-enabled-flag>false</facebook-enabled-flag>
</product>
<product product-id="000100103H103-07546">
    <ean/>
    <upc/>
    <unit/>
    <min-order-quantity>1</min-order-quantity>
    <custom-attributes>
        <custom-attribute attribute-id="color">000100103H103-07546</custom-attribute>
    </custom-attributes>
    <pinterest-enabled-flag>false</pinterest-enabled-flag>
</product>

这是我尝试过的:

for x in  root.findall('dw:product/dw:custom-attributes/dw:custom-attribute[@attribute-id="color" and text()="000100103H103-07546"]', ns):
    print x.text

但我收到此错误消息:SyntaxError: invalid predicate

我认为这是因为text()不适用于 XML 包。有没有办法做到这一点lxml

标签: pythonxmlxpathelementtree

解决方案


推荐阅读