XPath中获取所有后代文本节点的核心表达式是//text(),它返回文本节点集合而非拼接字符串;实际应用中常配合normalize-space()过滤空白节点,并需宿主语言完成最终字符串拼接。

XPath 中没有直接的“并集”操作符来合并多个文本节点的内容,但可以通过 //text() 选中所有后代文本节点(非空、非空白的需额外过滤),这是最接近“所有后代文本节点集合”的表达方式。
//text() 会选取当前上下文节点的所有后代元素中的所有文本节点(包括空白、换行等)。注意:它返回的是文本节点的集合,不是字符串拼接结果。
$x('//div//text()')
实际使用中,常需排除仅含空白符的节点,可用 normalize-space() 配合布尔判断:
//*/text()[normalize-space()] —— 只选内容经去首尾空格、压缩中间空白后非空的文本节点//text()[string-length(normalize-space()) > 0]
<div>\n <p>hello</p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/ai/955">
<img src="https://img.php.cn/upload/ai_manual/001/503/042/68b6d17fe12d9828.png" alt="Glarity">
</a>
<div class="aritcle_card_info">
<a href="/ai/955">Glarity</a>
<p>Glarity是一款免费开源的AI浏览器扩展,提供YouTube视频总结、网页摘要、写作工具等功能,支持免费的镜像翻译,电子邮件写作辅助,AI问答等功能。</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="Glarity">
<span>131</span>
</div>
</div>
<a href="/ai/955" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="Glarity">
</a>
</div>
\n</div> 中的换行符文本节点XPath 本身不提供字符串拼接函数(XPath 1.0 无 string-join()),所以“并集”若指拼成一个字符串,需外部处理:
string-join(//*/text()[normalize-space()], '')
[t.strip() for t in tree.xpath('//*/text()') if t.strip()]''.join(...) 拼接基本上就这些。记住核心是 //text(),其余都是围绕它做清洗或后续整合。
以上就是XPath怎么选择所有后代文本节点的并集的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号