Victor Mukherjee
Victor Mukherjee

Reputation: 11025

xslt select distinct valued elements

Consider the following xml:

<Images>
 <Extra1>a</Extra1>
 <Extra2>b</Extra2>
 <Img1>img1</Img1>
 <Img2>img2</Img2>
 <Img3>img2</Img3>
 <Img4>img1</Img4>
</Images>

I want a collection of distinct values for elements Img1, Img2, Img3, Img4 so that the output node set has values img1 and img2. I have used xsl:key earlier, but that requires all elements name to be same. How can I achieve that for different element names?

Upvotes: 0

Views: 153

Answers (1)

JLRishe
JLRishe

Reputation: 101652

You can do this:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
  <xsl:key name="kImageValue" match="Images/*[starts-with(local-name(), 'Img')]"
           use="."/>

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

  <xsl:template match="Images">
    <xsl:copy>
      <xsl:apply-templates select="*[generate-id() = generate-id(key('kImageValue', .)[1])]" />
    </xsl:copy>
  </xsl:template>

  <xsl:template match="Images/*">
    <Value>
      <xsl:value-of select="."/>
    </Value>
  </xsl:template>
</xsl:stylesheet>

When run on your sample input, the result is:

<Images>
  <Value>img1</Value>
  <Value>img2</Value>
</Images>

Upvotes: 1

Related Questions