如何使用 xslt 删除重复的 xml 节点? [英] How to remove duplicate xml-nodes using xslt?

查看:27
本文介绍了如何使用 xslt 删除重复的 xml 节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当所有变量都使用 xslt 完全匹配时,我想删除重复项.

I want to remove duplicates when all variables are exact matches using xslt.

在这个 xml 节点 3 应该被删除,因为它是节点 1 的完美副本.

In this xml node 3 should be removed because it is a perfect copy of node 1.

<root> 
    <trips> 
      <trip> 
        <got_car>0</got_car> 
        <from>Stockholm, Sweden</from> 
        <to>Gothenburg, Sweden</to> 
        <when_iso>2010-12-06 00:00</when_iso> 
      </trip>
      <trip> 
        <got_car>0</got_car> 
        <from>Stockholm, Sweden</from> 
        <to>New york, USA</to> 
        <when_iso>2010-12-06 00:00</when_iso> 
      </trip>
      <trip> 
        <got_car>0</got_car> 
        <from>Stockholm, Sweden</from> 
        <to>Gothenburg, Sweden</to> 
        <when_iso>2010-12-06 00:00</when_iso> 
      </trip>
      <trip> 
        <got_car>1</got_car> 
        <from>Test, Duncan, NM 85534, USA</from> 
        <to>Test, Duncan, NM 85534, USA</to> 
        <when_iso>2010-12-06 00:00</when_iso> 
      </trip> 
    <trips> 
<root>

推荐答案

这段代码:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>

<xsl:key name="trip-tth" match="/root/trips/trip" use="concat(got_car, '+', from, '+', to, '+', when_iso)"/>

<xsl:template match="root/trips">   
    <xsl:copy>
        <xsl:apply-templates select="trip[generate-id(.) = generate-id( key ('trip-tth', concat(got_car, '+', from, '+', to, '+', when_iso) ) )]"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="trip">
    <xsl:copy-of select="."/>
</xsl:template>

</xsl:stylesheet>

会成功.

它利用了一个事实,即应用于键的 generate-id() 将采用匹配给定条件的第一个节点的 id.在我们的例子中,标准是每个行程子元素的串联值.

It utilizes the fact that generate-id() applied to a key will take the id of the first node, that matches a given criteria. And in our case criteria is concatenated value of each trip child element.

这篇关于如何使用 xslt 删除重复的 xml 节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆