tags:

views:

41

answers:

2
+1  Q: 

XSLT - nested loop

Hi

I'm having trouble with an XSLT to loop through all the rows, and then all the columns in each row element.

So if this is the XML I have:

<root>
<subelement>
<rows>
<row title="Row1">
  <column title="A" />
  <column title="B" />
</row>
<row title="Row2">
  <column title="C" />
  <column title="D" />
</row>
</rows>
</subelement>
</root>

I would like output like this:

<h1>Row1</h1>
<ul>
  <li>A</li>
  <li>B</li>
</ul>
<h1>Row2</h1>
<ul>
  <li>C</li>
  <li>D</li>
</ul>

Regards

Peter

+1  A: 

This transformation:

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

 <xsl:template match="row">
     <h1><xsl:value-of select="@title"/></h1>
     <ul>
       <xsl:apply-templates/>
     </ul>
 </xsl:template>

 <xsl:template match="column">
   <li><xsl:value-of select="@title"/></li>
 </xsl:template>
</xsl:stylesheet>

when applied on the provided XML document:

<root>
    <subelement>
        <rows>
            <row title="Row1">
                <column title="A" />
                <column title="B" />
            </row>
            <row title="Row2">
                <column title="C" />
                <column title="D" />
            </row>
        </rows>
    </subelement>
</root>

produces the wanted output:

<h1>Row1</h1>
<ul>
   <li>A</li>
   <li>B</li>
</ul>
<h1>Row2</h1>
<ul>
   <li>C</li>
   <li>D</li>
</ul>
Dimitre Novatchev
A: 

This is a book I can recommend to learn XSLT:

XSLT: Programmer's Reference, 2nd Edition, Michael Kay

Also, this website is very handy, it even has an online XSLT tester: http://www.w3schools.com/xsl/default.asp

Nicki