首页 > 解决方案 > 关于布尔运算符的Python问题elemetree

问题描述

有没有办法在 findall 命令的 xpath 中使用布尔运算符。例如: root.findall("./example/[value='a' or 'b']/example2"

标签: pythonxml

解决方案


无法让 XPATH 在其中工作,ElementTree但能够使其在lxml.

不清楚value是属性还是子级,example所以我同时显示。

import lxml.etree as ET

data = '''\
<abc>
    <example value="a">
        <example2>foo</example2>
    </example>
    <example value="b">
        <example2>bar</example2>
    </example>
    <example value="x">
        <example2>not this</example2>
    </example>
</abc>
'''

root = ET.fromstring(data)
for e in root.xpath('./example[@value="a" or @value="b"]/example2'):
    print(e.text)

data2 = '''\
<abc>
    <example>
        <value>a</value>
        <example2>abc</example2>
    </example>
    <example>
        <value>b</value>
        <example2>def</example2>
    </example>
    <example>
        <value>not this</value>
        <example2>xyz</example2>
    </example>
</abc>
'''

root = ET.fromstring(data2)
for e in root.xpath('./example[value="a" or value="b"]/example2'):
    print(e.text)

推荐阅读