You need to enable JavaScript to run this app. 如何修正XSLT实现同层级重复节点转换为指定XML格式
优惠活动
大模型
产品
解决方案
定价
更多

如何修正XSLT实现同层级重复节点转换为指定XML格式

修正说明

你的原代码存在两个核心问题:

  1. 缺少<original_list>节点包裹所有<list>条目
  2. 循环逻辑层级错误:你以CurrenInfo为单位生成<list>,导致同一个CurrenInfo下的多个CurrentChildInfo被合并到同一个<list>里,应该以CurrentChildInfo为单位生成<list>,再从上层节点取对应的current_id值

修正后完整XSLT代码

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>
  
  <xsl:template match="Body">
    <Info>
      <xsl:for-each select="//Grp[@Name='Root']/Grp[@Name='Info']">
        <!-- 输出parent_id字段 -->
        <parent_id>
          <xsl:value-of select="Parm[@Name='parent_id']/@Val"/>
        </parent_id>
        <!-- 添加要求的original_list外层包裹节点 -->
        <original_list>
          <!-- 遍历每个CurrentChildInfo生成对应的list节点 -->
          <xsl:for-each select=".//Grp[@Name='CurrentChildInfo']">
            <list>
              <!-- 从上层CurrenInfo节点取对应current_id值 -->
              <current_id>
                <xsl:value-of select="ancestor::Grp[@Name='CurrenInfo']/Parm[@Name='current_id']/@Val"/>
              </current_id>
              <!-- 输出当前节点下的Name、Value字段 -->
              <xsl:for-each select="Parm">
                <xsl:element name="{@Name}">
                  <xsl:value-of select="@Val"/>
                </xsl:element>
              </xsl:for-each>
            </list>
          </xsl:for-each>
        </original_list>
      </xsl:for-each>
    </Info>
  </xsl:template>
</xsl:stylesheet>

运行上述代码即可输出你要求的目标格式。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 00:51:00