Use for-each loop to output table row : table « XSLT stylesheet « XML Tutorial






File: Data.xml
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="Transform.xslt"?>

<INVENTORY>
   <BOOK InStock="yes">
      <TITLE>title 1</TITLE>
      <AUTHOR Born="1835">author 1</AUTHOR>
      <BINDING>paperback</BINDING>
      <PAGES>298</PAGES>
      <PRICE>$5.49</PRICE>
   </BOOK>
   <BOOK InStock="no">
      <TITLE>Leaves of Grass</TITLE>
      <AUTHOR Born="1819">W</AUTHOR>
      <BINDING>hardcover</BINDING>
      <PAGES>462</PAGES>
      <PRICE>$7.75</PRICE>
   </BOOK>
</INVENTORY>


File: Transform.xslt

<?xml version="1.0"?>
<xsl:stylesheet
   version="1.0" 
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

   <xsl:template match="/">
      <HTML>
      <HEAD>
         <TITLE>Books in Stock</TITLE>
      </HEAD>
      <BODY>
      <H2>Books In Stock</H2>
      <TABLE BORDER="1" CELLPADDING="5">
         <THEAD>
            <td>Title</TH>
            <td>Author</TH>
            <td>Binding Type</TH>
            <td>Number of Pages</TH>
            <td>Price</TH>
         </THEAD>
         <xsl:for-each select="INVENTORY/BOOK[@InStock='yes']">
            <TR ALIGN="CENTER">
               <TD>
                  <xsl:value-of select="TITLE"/>
               </TD>
               <TD>
                  <xsl:value-of select="AUTHOR"/> <BR/>
                  (born <xsl:value-of select="AUTHOR/@Born"/>)
               </TD>
               <TD>
                  <xsl:value-of select="BINDING"/>
               </TD>
               <TD>
                  <xsl:value-of select="PAGES"/>
               </TD>
               <TD>
                  <xsl:value-of select="PRICE"/>
               </TD>
            </TR>
         </xsl:for-each>
      </TABLE>
      </BODY>
      </HTML>
   </xsl:template>

</xsl:stylesheet>

Output:

<HTML>
   <HEAD>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <TITLE>Books in Stock</TITLE>
   </HEAD>
   <BODY>
      <H2>Books In Stock</H2>
      <TABLE BORDER="1" CELLPADDING="5">
         <THEAD>
            <td>Title</TH>
            <td>Author</TH>
            <td>Binding Type</TH>
            <td>Number of Pages</TH>
            <td>Price</TH>
         </THEAD>
         <TR ALIGN="CENTER">
            <TD>title 1</TD>
            <TD>author 1<BR>
               (born 1835)
               
            </TD>
            <TD>paperback</TD>
            <TD>298</TD>
            <TD>$5.49</TD>
         </TR>
      </TABLE>
   </BODY>
</HTML>








5.5.table
5.5.1.Use for-each loop to output table row
5.5.2.Table cell format
5.5.3.Format table cell with choose statement
5.5.4.Set table cell style with choose statement
5.5.5.generates a table with selected elements,with the number of elements per row given in the stylesheet