XSLT删除重复的子项

时间:2013-05-23 12:28:50

标签: xslt duplicates element children

我正在寻找一个XSLT转换来重复删除父元素的子元素。 在我的情况下,父母和孩子都被给予(即我不想重复删除任何元素的任何子女)。

例如,我想对<ID>的{​​{1}}个孩子进行重复数据删除

输入:

<ROWSET>

我希望输出为

<ROWSET>
    <ROW>
         <ID> 1 </ID>
         ...
         <ID> 1 </ID>
         ...
    </ROW>
    <ROW>
         <ID> 2 </ID>
         ...
         <ID> 2 </ID>
         ...
    </ROW>
    ...
</ROWSET>

其中'...'表示存在任意数量的任何其他标签。

编辑: 两个重复的孩子之间可能有任何东西

2 个答案:

答案 0 :(得分:2)

一种简单直接的方法来忽略id,它具有与同一父元素的前一元素相同的内容。

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >

    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match ="ID" >
        <xsl:if test="not (preceding-sibling::ID/text() = current()/text())" >
            <xsl:copy>
                <xsl:apply-templates select="@* | node()" />
            </xsl:copy>
        </xsl:if>
    </xsl:template>

</xsl:stylesheet>

答案 1 :(得分:1)

您有一个解决方案,但使用Muenchian grouping可能更有效:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:key name="equal" match="ROW/ID" use="concat(generate-id(..), '|', .)"/>

<xsl:template match="@* | node()">
  <xsl:copy>
    <xsl:apply-templates select="@* | node()"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="ROW/ID[not(generate-id() = generate-id(key('equal', concat(generate-id(..), '|', .))[1]))]"/>

</xsl:stylesheet>