Xpath 紧靠前一个同级必须包含属性
这是我的XML文件:Xpath 紧靠前一个同级必须包含属性,xpath,Xpath,这是我的XML文件: <w type="fruit-hard">apple</w> <w type="fruit-soft">orange</w> <w type="vegetable">carrot</w> 我得到了我想要的“orange”元素节点,但如何要求其类型为“fruit soft”?我的尝试(如下)返回“false” 您的原始XPath //w[@type='vegetable']/preceding-sibl
<w type="fruit-hard">apple</w>
<w type="fruit-soft">orange</w>
<w type="vegetable">carrot</w>
我得到了我想要的“orange”元素节点,但如何要求其类型为“fruit soft”?我的尝试(如下)返回“false”
您的原始XPath
//w[@type='vegetable']/preceding-sibling::w[1]
。。。相当于
//w[@type='vegetable']/preceding-sibling::w[position()=1]
。您可以根据需要向谓词添加其他条件:
//w[@type='vegetable']/preceding-sibling::w[position()=1 and @type='fruit-soft']
或者您可以添加一个单独的谓词
//w[@type='vegetable']/preceding-sibling::w[1][@type='fruit-soft']
请注意,此尝试:
//w[@type='vegetable']/preceding-sibling::w[1] and preceding-sibling::w[@type='fruit-soft']
返回
false
,因为和
两侧的部分分别求值,转换为类型布尔值
,并组合以生成最终结果。假设对其求值的上下文节点是文档根,则永远不会有与前面的同级::w[@type='fruit-soft']
匹配的节点。此外,即使存在这样的节点,该表达式也不要求匹配第一部分的节点与匹配第二部分的节点相同。谢谢。就在你回答之前,我有效地使用了你的“/w[@type='vegeture']/previous sibling::w[1][@type='fruit-soft']”方法,然后发现我的思路是正确的。非常感谢。
//w[@type='vegetable']/preceding-sibling::w[1][@type='fruit-soft']
//w[@type='vegetable']/preceding-sibling::w[1] and preceding-sibling::w[@type='fruit-soft']