Andy Boehm
Andy Boehm

Reputation: 43

How to select unique child nodes of all siblings in XSLT 1

I'm looking for the best way to get all unique (no duplicates) nested nodes of all sibling nodes. The node I'm am interested in is "Gases". The sibling nodes are "Content". My simplified XML:

<Collection>
  <Content>
    <Html>
     <root>
      <Gases>NO2</Gases>
      <Gases>CH4</Gases>
      <Gases>O2</Gases>
     </root>
    </Html>
  </Content>
  <Content>
    <Html>
     <root>
      <Gases>NO2</Gases>
      <Gases>CH4</Gases>
      <Gases>CO</Gases>
      <Gases>LEL</Gases>
      <Gases>NH3</Gases>
     </root>
    </Html>
  </Content>
</Collection>

Desired result: NO2 CH4 O2 CO LEL NH3

I'm new to XSLT so any help would be much appreciated. I've been trying to use XPATH, similar to here, but with no luck.

Upvotes: 0

Views: 686

Answers (1)

Ben L
Ben L

Reputation: 1312

This XSLT stylesheet will produce the desired output. Note that it relies on there being no duplicate Gases element inside a single Content element.

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

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

  <!-- Match Gases elements whose value does not appear in a Gases element inside a previous
       Content element. -->
  <xsl:template match="//Gases[not(. = ancestor::Content/preceding-sibling::Content//Gases)]">
    <xsl:value-of select="."/>
    <xsl:text> </xsl:text>
  </xsl:template>

  <!-- Need to override the built-in template for text nodes, otherwise they will still get
       printed out. -->
  <xsl:template match="text()"/>

</xsl:stylesheet>

Upvotes: 2

Related Questions