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

如何同时转换XML节点属性与内容?XSLT样式容器缺失问题

问题原因

你的XSLT代码中,匹配特定内容的var[contains(text(),'XXX')]模板,优先级高于通用的var模板。当XML里的var元素同时满足属性和内容匹配条件时,只会执行优先级更高的特定内容模板,仅输出替换后的文本,不会触发通用模板里的样式包裹逻辑。

解决方案

拆分元素样式处理与文本内容替换逻辑:让通用模板负责var元素的样式包裹,单独编写模板匹配var内部的文本节点来替换内容,两者即可同时生效。

修改后的完整XSLT代码

<!-- 通用模板:处理var元素的样式包裹 -->
<xsl:template match="var">
    <xsl:choose> 
        <xsl:when test="@style='font-weight:bold;'">
            <strong>
                <xsl:apply-templates/>
            </strong>
        </xsl:when>
        <xsl:when test="@styleclass='Interface'">
            <span style="color:white; background-color: rgb(98, 98, 98);">
                <xsl:apply-templates/>
            </span>
        </xsl:when> 
        <xsl:when test="@styleclass='Interface b'">
            <span style="color: rgb(98, 98, 98); background-color: rgb(233, 180, 0);">
                <xsl:apply-templates/>
            </span>
        </xsl:when>         
        <xsl:when test="@styleclass='Interface c'">
            <span style="color: black; background-color: rgb(234, 235, 237);">
                <xsl:apply-templates/>
            </span>
        </xsl:when> 
        <xsl:when test="@styleclass='Warning a'">
            <span style="color:#e74c3c">
                <xsl:apply-templates/>
            </span>
        </xsl:when>         
        <xsl:otherwise> 
            <xsl:apply-templates/>
        </xsl:otherwise> 
    </xsl:choose> 
</xsl:template>

<!-- 单独匹配var内部的文本节点,替换变量内容 -->
<xsl:template match="var/text()[contains(.,'BACKGROUND')]">
    Background
</xsl:template>

<xsl:template match="var/text()[contains(.,'COLOR PICKER')]">
    Color picker
</xsl:template>

<xsl:template match="var/text()[contains(.,'PARAGRAPH')]">
    Paragraph
</xsl:template>

<xsl:template match="var/text()[contains(.,'IMPORT DATA')]">
    Import data
</xsl:template>

原理说明

  • 通用var模板匹配整个元素,根据属性生成对应的span/strong标签,再通过<xsl:apply-templates/>触发内部文本节点的处理逻辑。
  • 文本节点模板仅匹配var内部的文本内容,负责将变量替换为目标文本,不会干扰外层的样式标签。

修改后,示例中的<var styleclass="Interface b">&lt;%BACKGROUND%&gt;</var>会被转换为:

<span style="color: rgb(98, 98, 98); background-color: rgb(233, 180, 0);">
    Background
</span>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 12:45:40