Remove second node with same id in xslt

344 views Asked by At

I need to remove some node whith same ID in a xml file using XSLT 2.0. The structure is:

<Root>
  <media tipo="immagine" id="1">
    <numero>14.1</numero>
  </media>
  <media tipo="immagine" id="2">
    <numero>14.2</numero>
  </media>
  <media tipo="immagine" id="1">
    <numero>14.1</numero>
  </media>
</Root>

and the result must be:

<Root>
  <media tipo="immagine" id="1">
    <numero>14.1</numero>
  </media>
  <media tipo="immagine" id="2">
    <numero>14.2</numero>
  </media>
</Root>

I have multiple with the same attribute ID value. Thanks

2

There are 2 answers

0
Martin Honnen On BEST ANSWER

Assuming the id is all you want to compare and check use

<xsl:key name="by-id" match="*" use="@id"/>

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

<xsl:template match="*[@id and not(. is key('by-id', @id)[1])]"/>
0
michael.hor257k On

Since you're using XSLT 2.0, you can do:

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

<xsl:template match="/Root">
    <Root>
        <xsl:for-each-group select="media" group-by="@id">
            <xsl:copy-of select="current-group()[1]"/>
        </xsl:for-each-group>
    </Root>
</xsl:template>

</xsl:stylesheet>