开发者

how to Display XML as a HTML table

I have an XML file that contains configuration info for some programs. The file looks something like:

<master>
  <childCat1>
     <param1>test1</param1>
     <param2>test2</param2>
   </childCat1>
  <childCat2>
     <item1>test3</item1>
     <item2>test4</item2>
  </childCat2>
</master>*

I want to create an XSL stylesheet to display the XML as a html table. Could someone suggest how I could use XSL to transform the XML into a table as shown below? I need to be able to add additional categories and parameters without having to revisit the stylesheet every time - would be great if the stylesheet understands that the xml will always have categories, parameters and values but not make any assumption about how many of each.

In the table I'd like 3 columns. I'd like the columns to display as:

Category    Parameter   Value
--------------------------------
childCat1   param1      test1
childCat1   param2      test2
-------------------------------- 
childcat2   item1       item1
childcat2   item2       item2

etc It would be a nice to have for the separator lines between categories to appear but I can live without them.

Thanks in advance for any assistance. If all else fails I'll write s开发者_如何学编程ome php code to do this but an XSL stylesheet would be much more versatile.

CLARIFICATION:

My preference is for XSL that knows only one thing in advance - that the XML has two levels of elements, categories and their immediate children. So no matter what I might add (or delete) - additional categories or children or whatever, the xsl works without manual updating.


I think this is what you are looking for

<?xml version="1.0" encoding="ISO-8859-1"?>
 <xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:template match="/master">
 <html><body>
 <table border="1">
  <tr bgcolor="yellow">
        <th style="text-align:left">Category</th>
        <th style="text-align:left">Parameter</th>
        <th style="text-align:left">Value</th>
      </tr>
   <xsl:apply-templates select="./*" mode='category' />

 </table>
</body></html>
 </xsl:template>

<xsl:template match='*' mode='category'>
<tr><td colspan='3'></td></tr>
<xsl:apply-templates select="./*" mode='parameter' />
</xsl:template>

<xsl:template match='*' mode='parameter'>
<tr>
<td><xsl:value-of select="name(..)"/></td>
<td><xsl:value-of select="name()"/></td>
<td><xsl:value-of select="."/></td>
</tr>

</xsl:template>
</xsl:stylesheet>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜