You need to enable JavaScript to run this app. XSLT 1.0如何通过IF构建换行分隔列表并移除末尾多余换行
优惠活动
大模型
产品
解决方案
定价
更多

XSLT 1.0如何通过IF构建换行分隔列表并移除末尾多余换行

XSLT生成换行分隔列表消除末尾空行方案

现有实现的问题根源是:每个符合条件的特征项末尾都拼接了换行符,因此最后一个有效项后面会多一个换行,导致末尾出现空行,可通过以下两种方案解决:

方法1:调整拼接逻辑(更稳定,推荐)

XSLT 2.0 及以上版本

直接将符合条件的特征存入序列,用string-join函数以换行符作为分隔符拼接,自动避免末尾多余换行:

<!-- 筛选所有值为yes的特征,生成对应文本序列 -->
<xsl:variable name="feature-list" as="item()*">
  <xsl:if test="pool='yes'">Pool</xsl:if>
  <xsl:if test="balcony='yes'">Balcony</xsl:if>
  <xsl:if test="garage='yes'">Garage</xsl:if>
</xsl:variable>
<!-- 用换行符拼接序列,无末尾换行 -->
<xsl:value-of select="string-join($feature-list, '&#10;')"/>

XSLT 1.0 兼容版本

通过「首项不加前缀、后续项加换行前缀」的逻辑拼接,避免末尾换行:

<xsl:variable name="pool">
  <xsl:if test="pool='yes'">Pool</xsl:if>
</xsl:variable>
<xsl:variable name="balcony">
  <xsl:if test="balcony='yes'">Balcony</xsl:if>
</xsl:variable>
<xsl:variable name="garage">
  <xsl:if test="garage='yes'">Garage</xsl:if>
</xsl:variable>

<xsl:variable name="features">
  <!-- 先输出第一个非空项 -->
  <xsl:if test="$pool != ''">
    <xsl:value-of select="$pool"/>
  </xsl:if>
  <!-- 后续项前面加换行 -->
  <xsl:if test="$balcony != ''">
    <xsl:if test="$pool != ''">
      <xsl:text>&#10;</xsl:text>
    </xsl:if>
    <xsl:value-of select="$balcony"/>
  </xsl:if>
  <xsl:if test="$garage != ''">
    <xsl:if test="$pool != '' or $balcony != ''">
      <xsl:text>&#10;</xsl:text>
    </xsl:if>
    <xsl:value-of select="$garage"/>
  </xsl:if>
</xsl:variable>

<xsl:value-of select="$features"/>

方法2:修剪现有结果的末尾换行

如果不想改动原有拼接逻辑,可以直接对最终结果做末尾换行清理:

<!-- 原有拼接逻辑不变,得到带末尾换行的$features -->
<xsl:variable name="features" select="concat($pool,$balcony,$garage)"/>
<!-- 替换末尾的换行符,XSLT 2.0+可用 -->
<xsl:value-of select="replace($features, '\n$', '')"/>

如果是XSLT 1.0,可以加非空判断后截取末尾换行:

<xsl:choose>
  <xsl:when test="$features != ''">
    <xsl:value-of select="substring($features, 1, string-length($features) - 1)"/>
  </xsl:when>
  <xsl:otherwise>
    <xsl:value-of select="$features"/>
  </xsl:otherwise>
</xsl:choose>

注意:该修剪方式仅在原有拼接逻辑确定每个有效项末尾都带换行时可用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 23:06:01