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

如何修改XSLT代码以保留目标元素Node3的原有属性?

如何在XSLT转换中保留节点属性

嘿,这个问题很好解决!你当前的XSLT里,<xsl:copy>只会复制Node3这个节点本身,不会自动把它的属性(attx="1" attry="2" attrz="3")一起复制,所以输出里Node3的属性就丢了。另外我还注意到原XSLT里有个语法小问题:<BasicEnum>的结束标签位置不对,导致结构不合法,我也一起帮你修正了。

修改后的XSLT代码

只需要在<xsl:copy>内部、<xsl:apply-templates/>之前,加上<xsl:copy-of select="@*"/>来复制当前节点的所有属性:

<xsl:template match="Node1/Node2/Node3">
  <xsl:copy>
    <!-- 复制Node3的所有属性 -->
    <xsl:copy-of select="@*"/>
    <xsl:apply-templates/>
    <BasicDouble attr1="104" attr2="12312" attr3="0" />
    <BasicEnum attr1="104" attr2="12312" attr3="0" >
      <Pair Key="0" Value="First"/>
      <Pair Key="1" Value="Last"/>
    </BasicEnum>
  </xsl:copy>
</xsl:template>

修正后的输出结果

现在运行这个修改后的XSLT,得到的结果会完整保留Node3的属性,同时正确添加你需要的新节点:

<Node1>
  <Node2>
    <Node3 attx="1" attry="2" attrz="3">
      <child1 att1="1" attr2="2" attr3="3"/>
      <child1 att1="1" attr2="2" attr3="3"/>
      <child1 att1="1" attr2="2" attr3="3"/>
      <BasicDouble attr1="104" attr2="12312" attr3="0" />
      <BasicEnum attr1="104" attr2="12312" attr3="0" >
        <Pair Key="0" Value="First"/>
        <Pair Key="1" Value="Last"/>
      </BasicEnum>
    </Node3>
  </Node2>
</Node1>

额外说明

如果你不需要保留所有属性,只想复制特定的几个,比如只保留attx和attry,可以把<xsl:copy-of select="@*"/>改成:

<xsl:copy-of select="@attx | @attry"/>

要是需要对属性做修改再复制,也可以用<xsl:attribute>逐个设置,但对于保留全部属性的场景,<xsl:copy-of select="@*"/>是最直接高效的方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:54:36