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

基于XSLT 1.0实现XML节点通用更新与插入的技术问询

通用XSLT 1.0实现:用参数XML更新/追加目标XML节点

需求说明:
将作为参数传入的源XML与目标XML合并:遍历源XML的所有子元素,若目标XML存在同名节点则更新其值,不存在则添加该节点。目前已通过硬编码节点名实现功能,现需要无需逐个指定节点名的通用解决方案。

参数XML(源数据)

<root>
<f1>1</f1>
<f2>2</f2>
<f3>3</f3>
</root>

输入XML(目标数据)

<root>
<f1>a</f1>
<FY>Y</FY>
<fz>Z</fz>
</root>

输出XML(合并结果)

<root>
<f1>1</f1>
<f2>2</f2>
<f3>3</f3>
<FY>Y</FY>
<fz>Z</fz>
</root>

当前硬编码代码片段

<xsl:param name="SourceData" />
<xsl:variable name="Source_xml" select="parse-xml($SourceData)" />

<xsl:template match="f1">
  <f1><xsl:value-of select="$Source_xml//f1"/></f1>
</xsl:template>
<xsl:template match="f2">
  <f2><xsl:value-of select="$Source_xml//f2"/></f2>
</xsl:template>
<xsl:template match="f3">
  <f3><xsl:value-of select="$Source_xml//f3"/></f3>
</xsl:template>

通用XSLT 1.0解决方案

以下是无需硬编码节点名的通用实现,核心思路是利用xsl:key快速匹配同名节点,结合模板完成更新、追加逻辑:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <!-- 接收源XML字符串参数 -->
  <xsl:param name="SourceData" />
  <!-- 解析源XML为节点集 -->
  <xsl:variable name="Source_xml" select="parse-xml($SourceData)" />
  
  <!-- 为源XML的子元素建立节点名索引 -->
  <xsl:key name="source-elements" match="$Source_xml/root/*" use="local-name()" />

  <!-- 保留根节点结构,处理内部节点 -->
  <xsl:template match="root">
    <root>
      <!-- 先处理目标XML现有节点 -->
      <xsl:apply-templates select="@* | node()" />
      <!-- 追加源XML独有的节点 -->
      <xsl:apply-templates select="$Source_xml/root/*[not(key('source-elements', local-name(), ../..))]" />
    </root>
  </xsl:template>

  <!-- 处理目标XML元素节点:优先使用源XML值,无则保留原值 -->
  <xsl:template match="root/*">
    <xsl:variable name="current-name" select="local-name()" />
    <xsl:element name="{$current-name}">
      <xsl:choose>
        <xsl:when test="key('source-elements', $current-name, $Source_xml)">
          <xsl:value-of select="key('source-elements', $current-name, $Source_xml)" />
        </xsl:when>
        <xsl:otherwise>
          <xsl:value-of select="." />
        </xsl:otherwise>
      </xsl:choose>
    </xsl:element>
  </xsl:template>

  <!-- 通用复制模板:保留属性、文本等其他节点类型 -->
  <xsl:template match="@* | text() | comment() | processing-instruction()">
    <xsl:copy />
  </xsl:template>
</xsl:stylesheet>

关键逻辑说明

  1. 索引建立:通过xsl:key为源XML子元素创建节点名索引,提升同名节点的查找效率。
  2. 根节点处理:先处理目标XML现有节点,再追加源XML中目标没有的节点,保证节点完整性。
  3. 元素节点处理:对目标XML的每个元素,检查源XML是否存在同名节点,存在则替换值,否则保留原内容。
  4. 通用复制:确保属性、注释等非元素节点被原样保留,增强代码通用性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 21:43:18