此 xpath 返回类 theclass 的两个 div,我想根据它具有特定文本内容的跨度进行匹配。 (现实世界中跨度嵌套在许多节点下)所以我不想从父节点指定跨度的整个路径。
我只想返回第一个 div。
XPATH
//div[contains(@class, "theclass")][//span[text()="this"]]
HTML/XML
<html>
<div class="theclass">
<ul>
<li>
<strong>f</strong>
<span>this</span>
</li>
</ul>
</div>
<div class="theclass">
<ul>
<li>
<strong>g</strong>
<span>no</span>
</li>
</ul>
</div>
<div class="notclass">
<ul>
<li>
<strong>h</strong>
<span>not</span>
</li>
</ul>
</div>
</html>
最佳答案
通过添加 在当前父级
:div
的上下文中进行搜索。
//div[contains(@class, "theclass") and .//span="this"]
演示(使用 xmllint
):
$ xmllint index.html --xpath '//div[contains(@class, "theclass") and .//span="this"]'
<div class="theclass">
<ul>
<li>
<strong>f</strong>
<span>this</span>
</li>
</ul>
关于html - xpath 根据(相对)子内容选择父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29401845/