2011-08-16 83 views
3

我有一个XML文件,其中包含某些程序的配置信息。 该文件看起来是这样的:如何将XML显示为HTML表格

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

我想创建一个XSL样式表来显示XML作为HTML表格。 有人可以建议我如何使用XSL将XML转换为表格,如下所示? 我需要能够添加额外的类别和参数,而不必每次都重新访问样式表 - 如果样式表能够理解xml总是具有类别,参数和值,但不对每个样式表中的数量做出任何假设,那将会很好。

在表中,我想要3列。我想的列显示为:

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

等 这将是一个不错的了类之间的分割线出现,但我生活中可以没有他们。

在此先感谢您的帮助。如果一切都失败了,我会写一些PHP代码来做到这一点,但一个XSL样式表会更加多才多艺。

澄清:

我的选择是对XSL是只知道一件事提前 - 即XML具有元素,类别及其直系子的两个层次。因此,无论我添加(或删除)什么 - 其他类别或子项或其他,xsl都可以在不进行手动更新的情况下运行。

回答

0

我认为这是你在找什么

<?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>