首页 > 解决方案 > XPath 连接两个孩子

问题描述

我知道这是一个常见问题(我在 xpath XPath 中发现Concatenate multiple node values in xpath XPath join multiple elements and some others),但对于我的生活,我无法弄清楚。我有以下 HTML:

<div class="product-card__price__new"><span class="product-card__price__euros">0.</span> <span class="product-card__price__cents">69</span></div>

我需要从中提取 0.69。我尝试了以下 XPATH:

'.//*[@class="product-card__price__new"]/concat(/span/text(), following-sibling::span[1]/text)'
'.//*[@class="product-card__price__new"]/span/text()/concat(., following-sibling::span[1]/text)'
'.//*[@class="product-card__price__new"]/text()'

但我一直一无所获。提取它的正确表达是什么?

标签: htmlxpath

解决方案


它比这简单得多。元素的字符串值是其所有后代文本节点的串联。所以这只是

string(.//*[@class="product-card__price__new"])

在许多情况下,您不需要对 string() 的调用,因为它是隐式的。

大多数时候,人们使用text()它们时(a)使事情过于复杂和/或(b)弄错了。


推荐阅读