首页 > 解决方案 > XPATH 子字符串前后返回两个 html 标记之间的文本

问题描述

<h4>Start here</h4>
<p>Text stuff 1</p>
<p>Text stuff 2</p>
<h4>Stop here</h4>

我试图在一个查询之前和之后使用子字符串来获取具有以下文本的 h4 标记之间的所有内容:“从这里开始”,然后在文本“在此停止”之前停止

所以我的正确查询将返回文本:

Text Stuff 1
Text Stuff 2

无论我使用此查询的任何变体,它似乎都不起作用:

substring-before(substring-after(//h4[contains, 'Start here'),'//h4[contains, 'Stop here')

标签: htmlxpath

解决方案


您想要直接跟随特定的节点<h4>,其中“直接跟随”可以表示为“前面的第一个<h4>是我们开始的那个”(当然,所讨论的节点不是<h4>本身)。

这个表达式(*)

//h4[. = 'Start here']/following-sibling::*[not(self::h4) and preceding-sibling::h4[1][. = 'Start here']]

从此文档中选择

<body>
  <h4>Not relevant</h4>
  <p>Other stuff</p>
  <h4>Start here</h4>
  <p>Text stuff 1</p>
  <p>Text stuff 2</p>
  <h4>Stop here</h4>
  <p>Other stuff</p>
</body>

这些节点

<p>Text stuff 1</p>
<p>Text stuff 2</p>

您可以在主机应用程序中提取/加入它们的文本值。


(*)也可以写成//*[not(self::h4) and preceding-sibling::h4[1][. = 'Start here']],但是必须检查更多节点,即文档中的所有节点,而不是仅检查一个特定节点的下同级轴。


推荐阅读