Arun
Arun

Reputation: 435

XSL for-each node comparison

I have an input xml:

<ResultSet1>
     <set uid="80301707"/>
     <set uid="80301703"/>
     <set uid="80301705"/>
</ResultSet1>

<ResultSet2>
     <set itemNumber="80301707">
        <item>item2</item>
     </set>
     <set itemNumber="80301703">
        <item>item2</item>
     </set>
</ResultSet2>

I need to compare for-each of /ResultSet1/set@uid with for-each of /ResultSet2/set@itemNumber. If match is found, then I would need to select the value of /ResultSet2/set/item

Upvotes: 3

Views: 1111

Answers (3)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243469

Here is a complete, push-style solution (no <xsl:for-each> used):

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="ResultSet2/set[@itemNumber = /*/ResultSet1/set/@uid]">
     <xsl:copy-of select="*"/>
 </xsl:template>
 <xsl:template match="text()"/>
</xsl:stylesheet>

when this transformation is applied on the provided XML document:

<root>
    <ResultSet1>
        <set uid="80301707"/>
        <set uid="80301703"/>
        <set uid="80301705"/>
    </ResultSet1>
    <ResultSet2>
        <set itemNumber="80301707">
            <item>item1</item>
        </set>
        <set itemNumber="80301703">
            <item>item2</item>
        </set>
        <set itemNumber="80301704">
            <item>item3</item>
        </set>
    </ResultSet2>
</root>

the wanted, correct result is produced:

<item>item1</item>
<item>item2</item>

Upvotes: 3

Rookie Programmer Aravind
Rookie Programmer Aravind

Reputation: 12154

Assumed <root/> node for Input XML :)

<root>
  <ResultSet1>
    <set uid="80301707"/>
    <set uid="80301703"/>
    <set uid="80301705"/>
  </ResultSet1>

  <ResultSet2>
    <set itemNumber="80301707">
      <item>item1</item>
    </set>
    <set itemNumber="80301703">
      <item>item2</item>
    </set>
    <set itemNumber="80301704">
      <item>item3</item>
    </set>
  </ResultSet2>
</root>

XSLT Code:

  <xsl:template match="/root">
    <xsl:for-each select="ResultSet1">
      <xsl:for-each select="../ResultSet2/set[@itemNumber=//set/@uid]/item">
            <!--Do whatever you wish :) -->
        <xsl:copy>
          <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
      </xsl:for-each>
    </xsl:for-each>
  </xsl:template>

For the current XSL code: this will be the output:

<item>item1</item>
<item>item2</item>

hope it helped :)
lemme know if any queries

Upvotes: 1

Ludovic Kuty
Ludovic Kuty

Reputation: 4954

If you mean that a match is found where there is a node in set1 that matches a node in set2, then it is built into XPath. Cfr. http://www.w3.org/TR/xpath/#booleans

<xsl:for-each select="/ResultSet2/set/item[../@itemNumber = /ResultSet1/set/@uid]">
...
</xsl:for-each>

I haven't tested it.

Upvotes: 1

Related Questions