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

如何在Word模板的XSLT代码中隐藏未指定的PestLatin字段并避免生成空括号

解决PestLatin字段空括号问题的XSLT调整方案

嘿,我来帮你搞定这个烦人的空括号问题!你的现有代码只是检查PestLatin节点是否存在,但如果这些节点是空的(比如没有实际文本内容,或者只有空格),还是会输出()。咱们得调整判断条件,确保只有当存在有实际内容的PestLatin节点时,才输出括号和里面的内容。

问题根源

原来的<xsl:if>判断exists(//topic[@outputclass='pestsGroup']/p[@outputclass='PestLatin'])只验证节点存在性,哪怕节点是空字符串或全空格,依然会触发括号输出。

修改后的代码

<xsl:if test="exists(following-sibling::p[@outputclass='PestLatin' and preceding-sibling::p[@outputclass='TargetPest'][1][@id=$id] and normalize-space(.) != ''])">
  <w:t xml:space="preserve"> (</w:t>
  <xsl:for-each select="following-sibling::p[@outputclass='PestLatin' and preceding-sibling::p[@outputclass='TargetPest'][1][@id=$id] and normalize-space(.) != '']">
    <xsl:choose>
      <xsl:when test="position()=1">
        <w:t xml:space="preserve"><xsl:value-of select="."/></w:t>
      </xsl:when>
      <xsl:otherwise>
        <w:t xml:space="preserve">, <xsl:value-of select="."/></w:t>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:for-each>
  <w:t xml:space="preserve">)</w:t>
</xsl:if>

关键修改点

  • 调整<xsl:if>的判断条件:新增normalize-space(.) != '',确保只针对有非空文本内容的PestLatin节点进行判断。normalize-space()会自动去掉文本前后的空格,所以即使节点里只有空格,也会被视为空值,不会触发括号输出。
  • 同步修改<xsl:for-each>的选择条件:同样加上normalize-space(.) != '',避免循环处理空的PestLatin节点,确保输出的内容都是有效的文本值。

这样调整后,当没有指定任何PestLatin值(或者所有值都是空/空格)时,就不会输出空括号了,完全符合你的业务需求!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 22:47:38