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

如何使用XSLT将竖线分隔字符串转换为逐行输出

解决方案

要把竖线分隔的passId参数内容拆分成单独行显示,不同版本的XSLT有对应的实现方式,具体如下:

方式一:XSLT 2.0 及以上版本(推荐)

用XSLT 2.0自带的tokenize()函数直接分割字符串,再遍历输出每个分割项(同时清理前后多余空格):

<xsl:param name="passId"/>
<xsl:template match="/">
  <html>
    <head></head>
    <body>
      <xsl:for-each select="tokenize($passId, '\|')">
        <xsl:value-of select="normalize-space(.)"/>
        <br/>
      </xsl:for-each>
    </body>
  </html>
</xsl:template>
  • tokenize($passId, '\|'):按竖线|分割字符串(竖线在正则里是特殊字符,需用反斜杠转义)
  • normalize-space(.):去掉每个分割项前后的空格,适配原字符串里Line1 | Line2这类带空格的场景
  • 每个项后加<br/>实现换行

方式二:XSLT 1.0 版本

XSLT 1.0没有内置分割函数,需要通过递归模板完成拆分:

<xsl:param name="passId"/>
<xsl:template match="/">
  <html>
    <head></head>
    <body>
      <xsl:call-template name="splitString">
        <xsl:with-param name="input" select="$passId"/>
      </xsl:call-template>
    </body>
  </html>
</xsl:template>

<!-- 递归分割字符串的模板 -->
<xsl:template name="splitString">
  <xsl:param name="input"/>
  <xsl:choose>
    <!-- 存在竖线时,拆分并处理剩余内容 -->
    <xsl:when test="contains($input, '|')">
      <xsl:value-of select="normalize-space(substring-before($input, '|'))"/>
      <br/>
      <xsl:call-template name="splitString">
        <xsl:with-param name="input" select="substring-after($input, '|')"/>
      </xsl:call-template>
    </xsl:when>
    <!-- 处理最后一段内容 -->
    <xsl:otherwise>
      <xsl:value-of select="normalize-space($input)"/>
      <br/>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>
  • contains($input, '|'):判断当前字符串是否还有分隔符
  • substring-before/substring-after:分别截取分隔符前后的内容,剩余部分传入递归模板继续处理
  • normalize-space()同样用于清理多余空格,保证每行内容整洁

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 10:42:41