如何通过XSLT生成标准横向HTML表格?当前输出为纵向结构
问题描述
尝试用XSLT将XML数据转换为常规横向HTML表格,但当前输出始终是纵向结构。原XSLT代码如下:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="/"> <html> <body> <table> <xsl:apply-templates/> </table> </body> </html> </xsl:template> <xsl:template match="*"> <tr> <span style="background-color: #aaa;"> <xsl:value-of select="name()"/> : </span> <span style="background-color: #ccc;"> <xsl:value-of select="."/> </span> </tr> </xsl:template> <xsl:template match="*[*]"> <tr> <th style="border:2px solid #c55; font-size:120%;"> <xsl:value-of select="name()"/> </th> </tr> <tr> <td> <table> <xsl:apply-templates/> </table> </td> </tr> </xsl:template> </xsl:stylesheet>
问题原因
原代码核心逻辑是每个XML元素单独生成一行<tr>,嵌套元素还会生成子表格,自然呈现纵向堆叠结构。要实现横向表格,需把同级XML元素作为表格的列,而非行。
解决方案
以下是修正后的XSLT代码(适配常见的平级数据结构,如<root><item><name>张三</name><age>25</age></item></root>),可生成标准横向表格:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <!-- 生成HTML框架 --> <xsl:template match="/"> <html> <body> <table border="1" cellpadding="4"> <!-- 调用表头模板 --> <xsl:call-template name="table-header"/> <!-- 处理数据行 --> <xsl:apply-templates select="root/item"/> </table> </body> </html> </xsl:template> <!-- 生成表头:取第一个数据项的子元素名作为列标题 --> <xsl:template name="table-header"> <tr> <xsl:for-each select="root/item[1]/*"> <th style="background-color: #aaa; border:2px solid #c55;"> <xsl:value-of select="name()"/> </th> </xsl:for-each> </tr> </xsl:template> <!-- 生成数据行:每个item对应一行,子元素对应列 --> <xsl:template match="item"> <tr> <xsl:for-each select="*"> <td style="background-color: #ccc;"> <xsl:value-of select="."/> </td> </xsl:for-each> </tr> </xsl:template> </xsl:stylesheet>
关键改动说明
- 表头生成:通过
table-header模板,取第一个数据项的所有子元素名称作为横向表头列。 - 数据行生成:每个
<item>对应一行<tr>,其下的子元素分别生成<td>作为列。 - 移除原代码中每个元素单独生成行的逻辑,改用遍历同级元素生成列。
若你的XML结构不同,只需调整select路径即可适配。
内容的提问来源于stack exchange,提问作者Eas
相关产品推荐
相关产品推荐

