I need to nest xsl:for-each elements (or do something similar) to compare values to see if the inner element should be printed or not.

Roseanne Zhang

Here is an complete answer for you, include the XMLs XSLT and analysis.

Q. Should I use nested loop in this problem?
A: Interesting one, see the XML source and required result XML.
XML sourece

<people>
  <person>
    <name>John Doe</name>
    <ssn>111111111</ssn>
  </person>
  <person>
    <name>Mary May</name>
    <ssn>222222222</ssn>
  </person>
  <income>
    <ssn>111111111</ssn>
    <amount>33400</amount>
  </income>
  <income>
    <ssn>111111111</ssn>
    <amount>1000</amount>
  </income>
  <income>
    <ssn>222222222</ssn>
    <amount>25000</amount>
  </income>
  <income>
    <ssn>333333333</ssn>
    <amount>40000</amount>
  </income>
</people>  
Required XML result
<people>
  <person ssn="111111111" name="John Doe">
    <income amount="33400"/>
    <income amount="1000"/>
  </person>
  <person ssn="222222222" name="Mary May">
    <income amount="25000"/>
  </person>
</people>
  
XSLT soureces for comparison
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" />
  <xsl:key name="incomekey" 
    match="/people/income" 
    use="ssn" />
  <xsl:template match="/people" >
    <people>
      <xsl:apply-templates select="person" /> 
    </people>
  </xsl:template>
  <xsl:template match="person" >
    <person name="{name}" ssn="{ssn}" >
      <xsl:variable name="tmp" select="ssn" />
      <xsl:for-each select="key('incomekey', $tmp)" >
        <income amount="{amount}" />
      </xsl:for-each>
    </person>
  </xsl:template>
</xsl:stylesheet>
Important points here:
  • Loops here are nested. The outer loop is <xsl:apply-templates> on <person>, the inner loop is on the key
  • If inner loop is on <income>, then it would be very inefficient.
  • The <xsl:key> and key() function are playing the same role as index in database.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact