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

求助:使用XSLT实现指定XML数据转换的问题

问题分析与解决方案

原XSLT存在以下关键问题:

  • 模板匹配product/othertext会导致每个othertext节点单独触发模板,生成多个错误的父节点,且节点名拼写错误(应为collateraldetails而非collateraldetail)
  • for-each select="othertext"在当前othertext节点上下文下无法找到子节点,循环逻辑完全失效
  • 存在标签语法错误(如<xsl:value-of select="d104"/未闭合)
  • 模板结构不完整,choose和for-each的闭合逻辑混乱

正确的XSLT代码

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <!-- 身份模板:复制所有未被特殊处理的节点和属性 -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <!-- 处理product节点,替换所有othertext为collateraldetails并添加contentdetails -->
    <xsl:template match="product">
        <xsl:copy>
            <!-- 复制product下除othertext外的所有节点 -->
            <xsl:apply-templates select="@*|node()[not(self::othertext)]"/>
            
            <!-- 生成collateraldetails节点 -->
            <collateraldetails>
                <!-- 遍历所有othertext节点生成textcontent -->
                <xsl:for-each select="othertext">
                    <textcontent>
                        <!-- 根据d102的值生成对应的x426 -->
                        <xsl:choose>
                            <xsl:when test="d102 = '01'">
                                <x426>03</x426>
                            </xsl:when>
                            <xsl:when test="d102 = '02'">
                                <x426>02</x426>
                            </xsl:when>
                            <xsl:when test="d102 = '04'">
                                <x426>04</x426>
                            </xsl:when>
                        </xsl:choose>
                        <!-- 添加固定的x427节点 -->
                        <x427>00</x427>
                        <!-- 复制d104节点 -->
                        <xsl:apply-templates select="d104"/>
                    </textcontent>
                </xsl:for-each>
            </collateraldetails>
            
            <!-- 添加固定的contentdetails节点 -->
            <contentdetails>
                <contentitem>
                    <b288>Main Title</b288>
                </contentitem>
            </contentdetails>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

代码说明

  1. 身份模板:负责复制XML中所有未被自定义模板处理的节点和属性,保证原有节点(如a001、a002等)不受影响
  2. product节点模板:
    • 先复制product下除othertext外的所有子节点
    • 生成单个collateraldetails父节点,遍历所有othertext生成对应的textcontent子节点
    • 通过choose逻辑根据d102的文本值替换为指定的x426节点内容
    • 添加固定的x427节点,并复制原d104节点内容
    • 最后添加要求的固定contentdetails节点

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 18:01:22