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

XSLT 1.0如何将指定元素复制到特定目标元素之后

调整方案

核心逻辑是将插入逻辑绑定到f元素的处理流程上,而非在part节点处理末尾追加内容,这样可以自动适配f的动态位置,无需通过索引定位。

修改后完整XSLT代码

<xsl:stylesheet version="1.0"
            xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
            >
<xsl:strip-space  elements="*"/>
<xsl:output omit-xml-declaration="no" indent="yes"/>
<!-- 身份复制模板:原样复制所有未匹配到特殊规则的节点和属性 -->
<xsl:template match="node()|@*">
    <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
</xsl:template>
<!-- 匹配第二个element下part里的f元素,插入g、h到f之后 -->
<xsl:template match="//root/element[2]/part/f">
    <!-- 先原样复制f元素本身 -->
    <xsl:copy>
        <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
    <!-- 定义源part节点变量,简化后续引用 -->
    <xsl:variable name="sourcePart" select="../../element[1]/part"/>
    <!-- 不存在g时复制源g -->
    <xsl:if test="not(../g)">
        <xsl:copy-of select="$sourcePart/g"/>
    </xsl:if>
    <!-- 不存在h时复制源h -->
    <xsl:if test="not(../h)">
        <xsl:copy-of select="$sourcePart/h"/>
    </xsl:if>
</xsl:template>
</xsl:stylesheet>

关键改动说明

  • 移除了原来匹配//root/element[2]/part的模板,避免在part所有子节点处理完后追加内容
  • 新增针对第二个element下part中f元素的匹配规则:在完成f元素的复制后,立刻插入需要补充的g、h元素
  • f之后的原有节点(如示例中的z)会继续按原有顺序处理,不会打乱原有结构,完美适配动态位置的f元素

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 15:15:03