XSLT 1.0 对指定元素内字符应用模板格式化并排除abbr元素
适配XSLT 1.0的文本格式化实现方案
核心实现逻辑
- 完全隔离
<abbr>元素管辖范围的所有内容,不做任何字符匹配与格式调整 - 对
<l>、<add>等其他元素内的非abbr范围文本,逐字符拆分匹配目标内容(示例中为字母"e"),匹配到的字符用<strong>标签包裹 - 严格适配XSLT 1.0语法,不依赖高版本扩展能力
完整可复用XSLT代码
在现有XSLT头配置的基础上,追加以下模板逻辑即可实现需求:
<!-- 匹配<l>元素,生成要求的blockquote包裹结构 --> <xsl:template match="l"> <blockquote> <p> <xsl:apply-templates select="node()"/> </p> </blockquote> </xsl:template> <!-- 匹配<add>元素,移除原有XML标签,直接处理内部文本内容 --> <xsl:template match="add"> <xsl:apply-templates select="node()"/> </xsl:template> <!-- 非abbr管辖范围的文本节点:触发目标字符匹配逻辑 --> <xsl:template match="text()[not(ancestor::abbr)]"> <xsl:call-template name="process-text"> <xsl:with-param name="content" select="."/> </xsl:call-template> </xsl:template> <!-- abbr管辖范围的文本节点:原样输出,不做任何修改 --> <xsl:template match="text()[ancestor::abbr]"> <xsl:value-of select="."/> </xsl:template> <!-- 递归处理文本:逐字符匹配目标内容 --> <xsl:template name="process-text"> <xsl:param name="content"/> <xsl:param name="target-char" select="'e'"/> <xsl:if test="string-length($content) > 0"> <xsl:variable name="current-char" select="substring($content, 1, 1)"/> <xsl:choose> <!-- 匹配到目标字符时,用strong标签包裹 --> <xsl:when test="$current-char = $target-char"> <strong> <xsl:value-of select="$current-char"/> </strong> </xsl:when> <!-- 非目标字符直接原样输出 --> <xsl:otherwise> <xsl:value-of select="$current-char"/> </xsl:otherwise> </xsl:choose> <!-- 递归处理字符串剩余部分 --> <xsl:call-template name="process-text"> <xsl:with-param name="content" select="substring($content, 2)"/> </xsl:call-template> </xsl:if> </xsl:template>
自定义调整说明
- 修改匹配的目标字符/特殊符号,直接调整
process-text模板中$target-char的取值即可;如果需要匹配多个目标字符,只需在字符匹配的xsl:when判断中补充对应逻辑 - 如果需要保留
<l>、<add>等原有XML元素的标签或属性,将对应元素模板中的输出逻辑改为<xsl:copy><xsl:apply-templates select="node()"/></xsl:copy>即可 - 匹配范围的判断是通过祖先节点检测实现的,无论
<abbr>元素嵌套层级多深,其内部的所有文本都会被自动跳过处理
内容的提问来源于stack exchange,提问作者mindolianum
相关产品推荐
相关产品推荐

