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

使用XSLT标准化嵌套JSON时如何拆分数组生成多同名XML节点

解答

实现结论

你要的输出效果完全可以实现。

问题原因

你当前脚本的问题在于没有对JSON数组类型节点做单独遍历处理:player/midtbane 是数组节点,直接取该节点的文本值会输出整个数组的序列化字符串,也就是你得到的 ["offensiv-midtbane", "defensiv-midtbane"] 非预期结果。

修改后代码

你可以新增一层对数组子节点的遍历逻辑,适配两种不同结构的JSON输入,修改后的完整脚本如下:

const myXsl =
  fn.head(xdmp.unquote(
`
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">  
    <xsl:template match="/">
        <sport>
            <xsl:if test="exists(position)">
                <positionType>
                  <xsl:copy-of select="position"/>
                </positionType>
            </xsl:if> 
            
            <xsl:if test="exists(others)">
                <otherPosition>
                  <xsl:copy-of select="others"/>
                </otherPosition>
            </xsl:if>   

            <xsl:if test="exists(player)">
                <playerPosition>
                   <xsl:for-each select="player/child::node()">
                        <xsl:variable name="tagName" select="name()"/>
                        <!-- 判断当前节点是否为数组,是则遍历每个元素生成对应标签 -->
                        <xsl:choose>
                            <xsl:when test="count(./node()) > 1">
                                <xsl:for-each select="./node()">
                                    <xsl:element name="{$tagName}">  
                                        <xsl:value-of select="."/>
                                    </xsl:element>  
                                </xsl:for-each>
                            </xsl:when>
                            <xsl:otherwise>
                                <xsl:element name="{$tagName}">  
                                    <xsl:value-of select="."/>
                                </xsl:element>  
                            </xsl:otherwise>
                        </xsl:choose>
                   </xsl:for-each>
                </playerPosition>
            </xsl:if>            
        </sport>
    </xsl:template>
    
</xsl:transform>
`));
const doc = cts.doc('/soccer2.json')
xdmp.xsltEval(myXsl, doc)

效果说明

上述代码处理 /soccer2.json 时会自动遍历midtbane下的所有数组元素,生成两个独立的<midtbane>标签,完全符合你给出的预期输出格式,同时也兼容soccer1.json的嵌套数组结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 21:54:08