Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Displaying nested XML in groups

Status
Not open for further replies.

kohinoor24

Programmer
Jun 8, 2005
3
GB
Hi,
I have some example xml:

<Root>
<Rec>
<RecType>Type A</RecType>
<Words>testing output of A</Words>
</Rec>
<Rec>
<RecType>Type B</RecType>
<Words>testing output of B</Words>
</Rec>
<Rec>
<RecType>Type A</RecType>
<Words>testing output of A again</Words>
</Rec>
</Root>

I'm basically trying to output each 'RecType' as a heading with the corresponding 'Words' underneath. Using a xsl:for-each only results in all of the results being listed one after the other, whereas I actually want them grouped (i.e. Type A results and then Type B).

I did:

<xsl:for-each select="Rec/RecType">
<table>
<tr>
<td><xsl:value-of select="." /></td>
<td><xsl:value-of select="../Words" /></td>
</tr>
</table>
</xsl:for-each>

Any help appreciated.

Thanks.
 
either:
Code:
<xsl:for-each select="Rec"> 
 <table> 
  <tr> 
   <td><xsl:value-of select="RecType" /></td> 
   <td><xsl:value-of select="Words" /></td> 
  </tr> 
 </table> 
</xsl:for-each>

Or:
Code:
<table> 
 <tr> 
  <xsl:for-each select="Rec"> 
   <th><xsl:value-of select="RecType" /></th> 
  </xsl:for-each>
 </tr> 
 <tr> 
  <xsl:for-each select="Rec"> 
   <td><xsl:value-of select="Words" /></td> 
  </xsl:for-each>
 </tr> 
</table>

But there are easier and more efficient ways to set up table data...

Such as if you want to use the tagname as the header...
Look into node-name(node)

you could use something like:
Code:
<table> 
 <tr> 
  <xsl:for-each select="Rec[1]/*"> 
   <th><xsl:value-of select="node-name(.)" /></th> 
  </xsl:for-each>
 </tr> 
 <xsl:for-each select="Rec"> 
  <tr> 
   <xsl:for-each select="*"> 
    <td><xsl:value-of select="RecType" /></td> 
    <td><xsl:value-of select="Words" /></td> 
   </xsl:for-each>
  </tr> 
 </xsl:for-each>
</table>

Although, you should use keys in the above scenario, to avoid problems from missing or out-of-order elements...

Visit My Site
PROGRAMMER: (n) Red-eyed, mumbling mammal capable of conversing with inanimate objects.
 
Thank you for the reply, the code you suggested did generate different output but I should have been clearer in my original post (my fault, sorry!).

The output I'm currently getting is:

Type A testing output of A
Type B testing output of B
Type A testing output of A again


The output I want to generate is (lists 'Type A' entries together and so on):

Type A testing output of A
Type A testing output of A again
Type B testing output of B


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top