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

如何使用XSLT去除XML节点中的重复值?

Removing Duplicate Nodes from XML with XSLT

Hey there! To get rid of duplicate <item> nodes in your XML, the Muenchian Grouping technique is the tried-and-true approach in XSLT—it’s efficient and works with almost all XSLT processors out there.

First, let’s clarify: I’ll assume you want to flag an <item> as duplicate if all its child values (PLANT, SLOC, MATNR, CHARG) are identical. If you need to group by a subset of fields (like only MATNR + PLANT), you can tweak the solution easily.


Full XSLT Solution

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <!-- Define a key to group items by their unique field combination -->
    <xsl:key 
        name="uniqueItem" 
        match="item" 
        use="concat(PLANT, '|', SLOC, '|', MATNR, '|', CHARG)" 
    />

    <!-- Identity template: copies all nodes/attributes by default -->
    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

    <!-- Remove duplicate items: only keep the first occurrence in each group -->
    <xsl:template match="item[not(generate-id() = generate-id(key('uniqueItem', concat(PLANT, '|', SLOC, '|', MATNR, '|', CHARG))[1]))]"/>
</xsl:stylesheet>

How This Works

  • Key Definition: The uniqueItem key groups <item> nodes using a concatenated string of their child values. The | separator prevents accidental collisions (e.g., avoiding confusion between "INDIA150" and "INDIA" + "150").
  • Identity Template: This preserves your original XML structure—everything gets copied unless we explicitly override it.
  • Duplicate Removal: The final template matches any <item> that isn’t the first entry in its key group, and does nothing with it (so it gets excluded from the output).

Adjusting for Partial Field Grouping

If you only want to remove duplicates based on a subset of fields (say, PLANT and MATNR), just update the key and match condition:

<xsl:key 
    name="uniqueItem" 
    match="item" 
    use="concat(PLANT, '|', MATNR)" 
/>

<xsl:template match="item[not(generate-id() = generate-id(key('uniqueItem', concat(PLANT, '|', MATNR))[1]))]"/>

When you run this XSLT against your sample XML, you’ll end up with only one <item> per unique combination of the fields you specified.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:00:31