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

如何使用XSLT从XML中选取distinct去重的汽车厂商值

XSLT 按汽车厂商去重转换方案

现有代码问题梳理

  • 冗余内层循环:外层for-each已经通过Muenchian分组逻辑拿到了每个汽车厂商的唯一代表节点,不需要再嵌套内层循环遍历同厂商所有节点再加position()=1判断,冗余逻辑会增加出错概率
  • 语法错误:<xsl:apply-templates select="country" 缺少闭合标签,同时原输入XML中不存在country节点,该调用完全无效
  • 缺失国家映射规则:需要手动添加厂商所属国家的判断逻辑,才能输出对应国家字段

完整可运行实现代码

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:tns="http://替换为你实际的tns命名空间URI">
    <xsl:output method="xml" indent="yes"/>
    
    <!-- 按厂商分组的key定义 -->
    <xsl:key name="compMake" match="cars/car" use="make"/>

    <xsl:template match="/">
        <!-- 外层循环直接取每个厂商的唯一节点,完成去重 -->
        <xsl:for-each select="cars/car[generate-id(.) = generate-id(key('compMake', make)[1])]">
            <xsl:sort select="make"/>
            <tns:resource technicalType="application" appCode="6Y00">
                <tns:make lang="en">
                    <xsl:value-of select="substring(normalize-space(make),1,20)"/>
                </tns:make>
                <tns:country name="List">
                    <!-- 厂商所属国家映射逻辑 -->
                    <xsl:choose>
                        <xsl:when test="make = 'Ford'">USA</xsl:when>
                        <xsl:when test="make = 'Honda' or make = 'Toyota' or make = 'Nissan'">Japan</xsl:when>
                        <xsl:otherwise>Unknown</xsl:otherwise>
                    </xsl:choose>
                </tns:country>
            </tns:resource>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

注意事项

  • 请将代码中tns命名空间的URI替换为你业务场景下实际使用的命名空间地址
  • 国家映射规则可根据实际需求扩展,支持新增更多厂商对应的国家配置
  • 该实现基于XSLT 1.0标准,和你使用的Muenchian分组逻辑完全兼容,运行后会直接输出去重后的4个厂商节点,完全符合预期输出结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 13:48:04