如何使用XPath按属性名选择元素并排除相同子元素?
如何使用XPath按属性名选择元素并排除包含同类子元素的节点?
问题背景
给定以下HTML结构:
<div c-store="test"> <div c-text>Product Name</div> <div c-store="test"> <div c-text>Product Name</div> <div c-store="test"> <div c-text>Product Name</div> </div> </div> </div>
需要筛选出所有带有c-store="test"属性的<div>元素,但要求这些元素内部不能包含任何同样带有c-store="test"属性的子元素,最终期望得到的结果是:
<div c-store="test"> <div c-text>Product Name</div> </div>
解决方案
使用以下XPath表达式即可实现需求:
//div[@c-store="test" and not(.//div[@c-store="test"])]
表达式解释
//div[@c-store="test"]:匹配文档中所有带有c-store="test"属性的<div>元素and not(.//div[@c-store="test"]):添加筛选条件,排除那些自身后代节点中存在同样带有c-store="test"属性的<div>的节点- 组合后只会选中最底层、无同类嵌套的
c-store元素,完全符合需求
内容的提问来源于stack exchange,提问作者webifo
相关产品推荐
相关产品推荐

