How to convert XML to a HTML table using XSL for-each

Posted by Meeeee on Stack Overflow See other posts from Stack Overflow or by Meeeee
Published on 2009-08-26T08:10:00Z Indexed on 2010/06/02 1:03 UTC
Read the original article Hit count: 240

Filed under:
|

I am trying to convert some XML with XSL, to make the output look better and more readable for other users. I have some XML along the lines of:

<G>
  <OE>
    <example1>Sample 1</example1>
    <example2>Sample 2</example2>
    <var name="name1">
      <integer>1</integer>
    </var>
  </OE>
</G>

I want to get all the details from it and display it in a table so I use the following XSL code:

<xsl:stylesheet 
  version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>
  <xsl:template match="/">
    <html>
      <body>
        <h2>Heading</h2>
        <table border="1">
          <tr bgcolor="#3399FF">
            <th>Example 1</th>
            <th>Example 2</th>
            <th>Var name</th>
            <th>Int</th>
          </tr>
          <xsl:for-each select="G/OE">
            <xsl:for-each select="var">
              <tr>
                <td>
                  <xsl:value-of select="Example 1" />
                </td>
                <td>
                  <xsl:value-of select="Example 2" />
                </td>
                <td>
                  <xsl:value-of select="@name" />
                </td>
                <td>
                  <xsl:value-of select="integer" />
                </td>
              </tr>
            </xsl:for-each>
          </xsl:for-each>
        </table>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>

I know that the following XSL won't work properly. I want the output to be:

Sample 1, Sample 2, name1, 1 - in a table format.

My problem is I don't know how to do this. In the above XSL code it will only retrieve var and integer. If I only use the top <xsl:for-each>, then only the first two are retrieved.

I have tried moving the 2nd <xsl:for-each> after the first to have been selected, so between:

<td><xsl:value-of select="Example 2"/></td>

and

<td><xsl:value-of select="@name"/></td>

I get an error. Is there any way to solve this problem?

Thanks for the help.

© Stack Overflow or respective owner

Related posts about Xml

Related posts about xslt