OR条件不起作用的lxml xpath过滤器

时间:2014-09-12 00:10:28

标签: python xpath lxml

langs对象是通过解析此文件生成的lxml对象:http://www.loc.gov/standards/codelists/languages.xml

此xpath有效:

langs.node.xpath("//lang:language[lang:name='English']", namespaces={'lang':'info:lc/xmlns/codelist-v1'})[0].findtext('lang:name', namespaces={'lang': 'info:lc/xmlns/codelist-v1'})

当我添加 |的附加条件时lang:code ='英语' 喜欢这样:

langs.node.xpath("//lang:language[lang:name='English' | lang:code='English']", namespaces={'lang':'info:lc/xmlns/codelist-v1'})[0].findtext('lang:name', namespaces={'lang': 'info:lc/xmlns/codelist-v1'})

我收到错误:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "lxml.etree.pyx", line 1509, in lxml.etree._Element.xpath (src/lxml /lxml.etree.c:50717)
  File "xpath.pxi", line 318, in lxml.etree.XPathElementEvaluator.__call__ (src/lxml/lxml.etree.c:145969)
  File "xpath.pxi", line 238, in lxml.etree._XPathEvaluatorBase._handle_result (src/lxml/lxml.etree.c:144977)
  File "xpath.pxi", line 223, in lxml.etree._XPathEvaluatorBase._raise_eval_error  (src/lxml/lxml.etree.c:144785)
XPathEvalError: Invalid type

2 个答案:

答案 0 :(得分:5)

正确的语法是or,而不是|

nsmap={'lang': 'info:lc/xmlns/codelist-v1'}
langs.node.xpath("//lang:language[lang:name='English' or lang:code='English']",
  namespaces=nsmap)[0].findtext('lang:name', namespaces=nsmap)

答案 1 :(得分:3)

再过10分钟的谷歌搜索,我得到了答案:

我将 | 更改为

langs.node.xpath("//lang:language[lang:name='English' or lang:code='English']", namespaces={'lang':'info:lc/xmlns/codelist-v1'})[0].findtext('lang:name', namespaces={'lang': 'info:lc/xmlns/codelist-v1'})