<html>
<body>
<p>This is
<sub>subscripted</sub>
text1.
</p>
<p>This is
<sub>subscripted</sub>
text2.
</p>
<p>This is
<sub>subscripted</sub>
text3.
</p>
<p>This is
<sub>subscripted</sub>
text4.
</p>
<p>This is
<sub>subscripted</sub>
text5.
</p>
</body>
</html>
上面显示的是一个虚拟代码片段。我的要求是搜索"This is subscripted text1"
。找到这个后,我必须从下一个<p>
元素搜索另一个字符串匹配。如何使用xpath
来满足此要求。或者提出任何其他想法
答案 0 :(得分:0)
您正在寻找p
轴上的同级following-sibling
元素:
var p = document.evaluate('//p[normalize-space() = "This is subscripted text2."]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
if (p != null) {
var siblingP = document.evaluate('following-sibling::p[normalize-space() = "This is subscripted text4."]', p, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
if (siblingP != null) {
console.log(siblingP);
}
}
<html>
<body>
<p id="p0">This is
<sub>subscripted</sub>
text4.
</p>
<p id="p1">This is
<sub>subscripted</sub>
text1.
</p>
<p>This is
<sub>subscripted</sub>
text2.
</p>
<p>This is
<sub>subscripted</sub>
text3.
</p>
<p id="p4">This is
<sub>subscripted</sub>
text4.
</p>
<p>This is
<sub>subscripted</sub>
text5.
</p>
</body>
</html>