xpath select 基于(相对)子内容的父级
xpath select parent based on (relative) child content
This xpath returns both divs with the class theclass, 我想根据它具有特定文本内容的跨度进行匹配。 (真实世界的使用跨度嵌套在许多节点下)所以我不想从父节点指定跨度的整个路径。
我只想 return 第一个 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>
This xpath returns both divs with the class theclass, 我想根据它具有特定文本内容的跨度进行匹配。 (真实世界的使用跨度嵌套在许多节点下)所以我不想从父节点指定跨度的整个路径。
我只想 return 第一个 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>