Peter
Peter

Reputation: 545

XSLT - nested loop

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

Upvotes: 2

Views: 723

Answers (2)

Nicki
Nicki

Reputation: 1

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

Upvotes: 0

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243459

This transformation:

<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="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>

Upvotes: 2

Related Questions