带有以下特定兄弟情况的XPath

时间:2018-10-09 08:33:08

标签: xpath

我的结构看起来像这样

<p>
   <br>
       <b>Text to fetch </b>
   <br>
       "Some random text"
       <b>Text not to fetch</b>

我需要XPath,该XPath仅在 br 元素与其后继兄弟姐妹之间没有文本的情况下,才允许我获取其后继兄弟。

如果我做这样的事情

//br/following-sibling::b/text()[1]

它将同时获取Text to fetchText not to fetch,而我只需要Text to fetch

2 个答案:

答案 0 :(得分:1)

请尝试在XPath下面避免将b节点与前面的同级文本匹配:

//br/following-sibling::b[not(preceding-sibling::text()[1][normalize-space()])]/text()

答案 1 :(得分:1)

另一个可能的XPath:

//br/following-sibling::node()[normalize-space()][1][self::b]/text()

简要说明:

  • //br/following-sibling::node():找到在br元素后继的所有节点,这些节点在哪里。
  • [normalize-space()]:然后不为空(仅空白)。
  • [1]:对于找到的每个br,仅取该节点的第一个,然后..
  • [self::b]:检查节点是否为b元素,然后是否为b元素。
  • /text():返回作为b元素的子元素的文本节点