Search code examples
xmlxsltxslt-2.0exslt

Remove second node with same id in xslt


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


Solution

  • 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])]"/>