You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

normalize-space函数传参报错:不允许多项序列,求字符串合并方案

解决normalize-space()不接受多节点序列的问题

这个问题我太熟悉了!你遇到的报错本质是:normalize-space()要求第一个参数是单个字符串,但你的XPath表达式preceding-sibling::node()/text()返回了一个包含多个文本节点的序列,自然就触发了这个错误。

下面给你两种简单可行的解决方案,分XSLT版本来选:

方案1:XSLT 2.0+(推荐,更简洁)

XSLT 2.0及以上版本自带string-join()函数,可以直接把文本节点序列合并成单个字符串,之后再传给normalize-space()处理:

<xsl:value-of select="normalize-space(string-join(preceding-sibling::node()/text(), ''))"/>
  • string-join(序列, 分隔符):这里用空字符串''作为分隔符,会把所有文本节点无缝拼接成一个长字符串;
  • 再用normalize-space()去除首尾空格并压缩中间的多余空格,完美符合你的需求。

方案2:XSLT 1.0(兼容旧版本)

如果你的环境只能用XSLT 1.0,没有string-join(),可以写一个递归模板来拼接所有文本节点:

首先定义拼接模板:

<xsl:template name="concat-all-text">
  <xsl:param name="text-nodes"/>
  <!-- 递归拼接每个文本节点 -->
  <xsl:if test="$text-nodes">
    <xsl:value-of select="$text-nodes[1]"/>
    <xsl:call-template name="concat-all-text">
      <xsl:with-param name="text-nodes" select="$text-nodes[position() > 1]"/>
    </xsl:call-template>
  </xsl:if>
</xsl:template>

然后在需要的地方调用模板,再处理空格:

<!-- 先把所有文本节点拼接成单个字符串 -->
<xsl:variable name="combined-text">
  <xsl:call-template name="concat-all-text">
    <xsl:with-param name="text-nodes" select="preceding-sibling::node()/text()"/>
  </xsl:call-template>
</xsl:variable>

<!-- 再对拼接后的字符串做normalize-space处理 -->
<xsl:value-of select="normalize-space($combined-text)"/>

额外提示

如果你的需求是获取preceding-sibling节点下所有后代文本(包括子元素里的文本,比如你XML里<tag2>里的内容),可以把XPath改成preceding-sibling::node()//text(),再用上面的方法合并处理即可。

内容的提问来源于stack exchange,提问作者Ole

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:53:18