PythonFindall使用带有逻辑AND的xpath模式

2024-09-27 09:23:53 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的xpath:

<Unit>
  <_unit_type>FSP</_unit_type>
  <_logicalId>FSM1/FSP1</_logicalId>
</Unit>
<Unit>
  <_unit_type>FSP</_unit_type>
  <_logicalId>FSM1/FSP2</_logicalId>
</Unit>

所以我需要在我的xpath_pattern = .//Unit[_unitType='FSP'][starts-with(_logicalId,'FSM1']时找到len(root.findall(xpath_pattern)

如果我的模式是.//Unit[_unitType='FSP'],那么我的代码可以工作,我可以得到长度为2。但我需要添加另一个限定符,因为我的xml文件要复杂得多

Im获取SyntaxError:使用此模式时谓词无效 .//Unit[_unitType='FSP'][starts-with(_logicalId,'FSM1']


Tags: lentypewith模式unitxpathpatternstarts
3条回答

问题是lxml模块出于兼容性原因保留了两个不同的XPath引擎。从lxml FAQ

findall() is part of the original ElementTree API. It supports a simple subset of the XPath language, without predicates, conditions and other advanced features. [...]

xpath(), on the other hand, supports the complete power of the XPath language, including predicates, XPath functions and Python extension functions.

使用xpath()方法,如

from lxml import etree
root = etree.XML("""
<root> 
  <Unit> 
    <_unit_type>FSP</_unit_type>  
    <_logicalId>FSM1/FSP1</_logicalId> 
  </Unit>  
  <Unit> 
    <_unit_type>FSP</_unit_type>  
    <_logicalId>FSM1/FSP2</_logicalId> 
  </Unit> 
</root>""")
print(root.xpath(".//Unit[_unit_type='FSP'][starts-with(_logicalId,'FSM1')]"))

控制台输出:

[<Element Unit at 0x7fa1e0413140>, <Element Unit at 0x7fa1e04130f0>]

签入here

只需使用和运算符添加所需的条件

例如,如果您正在寻找特定的“单位”:

//Unit[_unit_type='FSP' and contains(.,'S')][starts-with(_logicalid,'FSM1') AND contains(.,'FSP1')]

您还可以使用“|”操作多个XPath。Xpath1 | Xpath2 | Xpath3 |。。。 如果您正在寻找与Unit不同的产品:

//Unit[_unit_type='FSP'][starts-with(_logicalid,'FSM1')]|//Entity[_unit_type='XYZ'][starts-with(_logicalid,'FSM1')]

你已经写信了

.//Unit[_unitType='FSP'][starts-with(_logicalId,'FSM1']

这会导致无效谓词语法错误。这是因为缺少右括号。试试这个:

.//Unit[_unitType='FSP'][starts-with(_logicalId,'FSM1')]

相关问题 更多 >

    热门问题