这是我的示例XML文档:
<div class="firstlevel" id="firstid">
<div class="secondlevel">
<span class="thirdlevel">
<a href="somelinknew">111 new</a>
<span class="fourthlevel">222</span>
</span>
<span class="thirdlevel">
<a href="somelinkold">333 old</a>
<span class="fourthlevel">444</span>
</span>
</div>
</div>
我试过这个XPath:
//*[@class='thirdlevel' and //text()[contains(.,'new')]]/span
但它返回两个值,222和444.为什么?我认为XPath正在寻找&#34; new&#34;但是也要显示返回&#34; old&#34;?!
主要问题是,代码也可以是这样的:
<div class="firstlevel" id="firstid">
<div class="secondlevel">
<span class="thirdlevel">
<a href="somelinkold">333 old</a>
<span class="fourthlevel">444</span>
</span>
</div>
</div>
或者像这样:
<div class="firstlevel" id="firstid">
<div class="secondlevel">
<span class="thirdlevel">
<a href="somelinknew">111 new</a>
<span class="fourthlevel">222</span>
</span>
</div>
</div>
或者就像这样:
<div class="firstlevel" id="firstid">
<div class="secondlevel">
</div>
</div>
答案 0 :(得分:3)
//text()
正在检查文档中的所有文本节点,因为//
正在从根级别检查自我或后代。相反,只需从当前节点.
开始在文本中查找“新”,然后从那里查找:
//*[@class='thirdlevel' and .//text()[contains(.,'new')]]/span
可以简化为
//*[@class='thirdlevel' and contains(.,'new')]/span