Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding unique nodes with xslt

Tags:

unique

xslt

xpath

I have an xml document that contains some "Item" elements with ids. I want to make a list of the unique Item ids. The Item elements are not in a list though - they can be at any depth within the xml document - for example:


<Node>
  <Node>
    <Item id="1"/>
    <Item id="2"/>
  </Node>
  <Node>
    <Item id="1"/>
    <Node>
      <Item id="3"/>
    </Node>
  </Node>
  <Item id="2"/>
</Node>

I would like the output 1,2,3 (or a similar representation). If this can be done with a single xpath then even better!

I have seen examples of this for lists of sibling elements, but not for a general xml tree structure. I'm also restricted to using xslt 1.0 methods. Thanks!

like image 607
tttppp Avatar asked Jun 08 '26 18:06

tttppp


2 Answers

Selecting all unique items with a single XPath expression (without indexing, beware of performance issues):

//Item[not(@id = preceding::Item/@id)]
like image 60
Erlock Avatar answered Jun 11 '26 07:06

Erlock


Try this (using Muenchian grouping):

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:key name="item-id" match="Item" use="@id" />
    <xsl:template match="/Node">
        <xsl:for-each select="//Item[count(. | key('item-id', @id)[1]) = 1]">
            <xsl:value-of select="@id" />,
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>
like image 41
Rubens Farias Avatar answered Jun 11 '26 07:06

Rubens Farias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!