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

如何在XSLT 1.0转换时替换XML节点中逗号后的文本

XSLT 1.0 实现作者名缩写为“et al”的解决方案

你当前使用translate()函数无法达成需求,因为该函数是逐个字符替换,会将逗号替换为"et al"的第一个字符(实际效果完全不符合预期)。在XSLT 1.0中,可以通过字符串截取和条件判断实现需求:当作者名包含逗号时,保留逗号前的第一个作者名,后续内容替换为" et al";无逗号时直接输出原作者名。

修改后的完整XSLT代码

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/> 
<xsl:template match="/">
<xsl:variable name="book-group" select="books/book[(price &lt; 30) and (title/@type='fiction')]"/>
<html>
<body>
<h2>Books</h2>
  <xsl:for-each select="books/book"> 
    <xsl:if test="price &lt; 30">
        <xsl:if test="title/@type='fiction'">
                <span id="title"><xsl:value-of select="title"/></span><br />
            <span id="authors">
                <!-- 核心逻辑:判断是否包含逗号,处理作者名缩写 -->
                <xsl:choose>
                    <xsl:when test="contains(authors, ',')">
                        <xsl:value-of select="substring-before(authors, ',')"/>
                        <xsl:text> et al</xsl:text>
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:value-of select="authors"/>
                    </xsl:otherwise>
                </xsl:choose>
            </span>
            <br />
            <span><xsl:value-of select="price"/></span><br />
            <span><xsl:value-of select="title/@type"/></span><br />
        </xsl:if>
    </xsl:if>
   </xsl:for-each>
   Total Cost : <xsl:value-of select="sum($book-group/price)"/>
   </body>
   </html>
  </xsl:template>
  </xsl:stylesheet>

关键代码说明

  • <xsl:choose> 实现分支判断:
    • contains(authors, ','):检查作者字符串中是否存在逗号(即是否有多个作者)
    • substring-before(authors, ','):截取逗号之前的第一个作者名
    • <xsl:text> et al</xsl:text>:拼接固定后缀,确保格式统一
    • 无逗号时直接输出原作者名,适配单个作者的场景

预期输出效果

针对你的XML示例,处理后符合条件的书籍会显示:

  • Book 5:Conte
  • Book 6:Anton et al

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 20:11:09