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

如何使用XSLT按id分组XML元素并将标签值用逗号拼接

解决方案

你的原有代码存在以下问题:

  • 仅按id做单次分组,未针对相同id下的非id子标签做二次分组,硬编码字段只能输出functional_manager__c.users,无法覆盖其他动态字段
  • <xsl:value-of>未指定separator=","参数,无法实现多值逗号拼接
  • 输出根节点错误写为<Sharingsettings>,不符合需求的<root>节点
  • id字段输出为大写<ID>,和期望的小写<id>不匹配
  • XPath误写//current-group(),双斜杠会全局搜索导致取到不属于当前分组的内容

可直接使用以下XSLT代码实现需求:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0" exclude-result-prefixes="xsl wd xsd this env"
 xmlns:wd="urn:com.workday/bsvc"
 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"
  xmlns:this="urn:this-stylesheet">

    <xsl:output indent="yes" method="xml" encoding="UTF-8"/>
  <xsl:template match="/">
  <root>
   <!-- 第一层按id分组 -->
   <xsl:for-each-group select="/root/row" group-by="id">
    <xsl:variable name="current-id" select="id"/>
    <!-- 第二层按同id下的非id子标签名分组 -->
    <xsl:for-each-group select="current-group()/*[not(local-name()='id')]" group-by="local-name()">
     <row>
      <id>
       <xsl:value-of select="$current-id"/>
       </id>
       <!-- 动态生成标签,拼接同组多值 -->
       <xsl:element name="{local-name()}">
        <xsl:value-of select="current-group()" separator=","/>
       </xsl:element>
      </row>
    </xsl:for-each-group>
    </xsl:for-each-group>
    </root>
    </xsl:template>
    </xsl:stylesheet>

代码逻辑说明:

  1. 先按id对所有row做第一层分组,归集所有相同id的行
  2. 对每组相同id的行,提取所有非id的子节点,再按节点名称做第二层分组,归集同id下同标签名的所有节点
  3. 对每个二次分组结果动态生成对应名称的标签,将组内所有节点的值用逗号拼接作为标签内容,输出结构完全匹配期望结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 19:06:04