我需要能够将平面xml数据集转换为html表,并且我很难找到符合我需要的语法示例.我想使用一个样式表,可以将类似的数据集转换为带有可变列的html表.这意味着除了“行”和“行”之外,它不能使用任何硬编码元素名称.
我之后的样式表将能够转换:
<?xml version="1.0" encoding="UTF-8"?> <rows> <row> <AccountId>BlPUAA0</AccountId> <AccountName>Initech</AccountName> <AcocuntStatus>Client</AcocuntStatus> </row> <row> <AccountId>CJxIAAW</AccountId> <AccountName>Intertrode</AccountName> <AcocuntStatus>Prospect</AcocuntStatus> </row> </rows>
成:
<table> <tr> <th>AccountId</th> <th>AccountName</th> <th>AcocuntStatus</th> </tr> <tr> <td>BlPUAA0</td> <td>Initech</td> <td>Client</td> </tr> <tr> <td>CJxIAAW</td> <td>Intertrode</td> <td>Client</td> </tr> </table>
还有这个:
<?xml version="1.0" encoding="UTF-8"?> <rows> <row> <AccountId>BlPUAA0</AccountId> <AccountName>Initech</AccountName> </row> <row> <AccountId>CJxIAAW</AccountId> <AccountName>Intertrode</AccountName> </row> </rows>
进入这个:
<table> <tr> <th>AccountId</th> <th>AccountName</th> </tr> <tr> <td>BlPUAA0</td> <td>Initech</td> </tr> <tr> <td>CJxIAAW</td> <td>Intertrode</td> </tr> </table>
解决方法
一个简单明了的解决方案:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:template match="/*"> <table><xsl:apply-templates select="row"/></table> </xsl:template> <xsl:template match="row[1]"> <tr><xsl:apply-templates select="*" mode="header"/></tr> <xsl:call-template name="standardRow"/> </xsl:template> <xsl:template match="row" name="standardRow"> <tr><xsl:apply-templates select="*"/></tr> </xsl:template> <xsl:template match="row/*"> <td><xsl:apply-templates select="node()"/></td> </xsl:template> <xsl:template match="row/*" mode="header"> <th><xsl:value-of select="name()"/></th> </xsl:template> </xsl:stylesheet>
当应用于第一个提供的XML文档时:
<rows> <row> <AccountId>BlPUAA0</AccountId> <AccountName>Initech</AccountName> <AcocuntStatus>Client</AcocuntStatus> </row> <row> <AccountId>CJxIAAW</AccountId> <AccountName>Intertrode</AccountName> <AcocuntStatus>Prospect</AcocuntStatus> </row> </rows>
产生了想要的正确结果:
<table> <tr> <th>AccountId</th> <th>AccountName</th> <th>AcocuntStatus</th> </tr> <tr> <td>BlPUAA0</td> <td>Initech</td> <td>Client</td> </tr> <tr> <td>CJxIAAW</td> <td>Intertrode</td> <td>Prospect</td> </tr> </table>
当应用于第二个提供的XML文档时:
<rows> <row> <AccountId>BlPUAA0</AccountId> <AccountName>Initech</AccountName> </row> <row> <AccountId>CJxIAAW</AccountId> <AccountName>Intertrode</AccountName> </row> </rows>
再次产生所需的正确结果:
<table> <tr> <th>AccountId</th> <th>AccountName</th> </tr> <tr> <td>BlPUAA0</td> <td>Initech</td> </tr> <tr> <td>CJxIAAW</td> <td>Intertrode</td> </tr> </table>