我已经通过了W3C学校的教程,我试图弄清楚,鉴于我拥有的xml数据结构,如何只打印一次表的标题!
这里是我的xml示例;
<data>
<slice name="TERM1">
<value name="a">23</value>
<value name="b">2342</value>
<value name="c">0.099</value>
<value name="d">0.09</value>
<value name="e">0.0730</value>
</slice>
<slice name="TERM2">
<value name="a">0.0655</value>
<value name="b">0.099</value>
<value name="c">0.002</value>
<value name="d">0.015</value>
<value name="e">0.099</value>
</slice>
</data>
所以'value'元素有一个'name'属性,我希望它成为表的列头。
现在我的XSLT看起来是这样的;
<?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="/">
<html>
<body>
<h2>Data</h2>
<table border="1">
<tr>
</tr>
<xsl:for-each select="data/slice">
<tr>
<th><xsl:value-of select="@name"/></th>
<xsl:for-each select="value">
<td><xsl:value-of select="@name"/><xsl:value-of select="."/></td>
</xsl:for-each>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
但是这给了我下面的输出;
TERM1 a23 b2342 c0.099 d0.09 e0.0730
TERM2 a0.0655 b0.099 c0.002 d0.015 e0.099
在我看来,最简单的方法是使用推送方法(xsl:apply-templates
而不是xsl:for-each
)和建模模板。
XML输入
<data>
<slice name="TERM1">
<value name="a">23</value>
<value name="b">2342</value>
<value name="c">0.099</value>
<value name="d">0.09</value>
<value name="e">0.0730</value>
</slice>
<slice name="TERM2">
<value name="a">0.0655</value>
<value name="b">0.099</value>
<value name="c">0.002</value>
<value name="d">0.015</value>
<value name="e">0.099</value>
</slice>
</data>
XSLT 1.0 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" method="html"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/*">
<table>
<xsl:apply-templates select="slice[1]" mode="header"/>
<xsl:apply-templates select="slice"/>
</table>
</xsl:template>
<xsl:template match="slice" mode="header">
<tr>
<th/>
<xsl:apply-templates select="value/@name" mode="header"/>
</tr>
</xsl:template>
<xsl:template match="@name" mode="header">
<th><xsl:value-of select="."/></th>
</xsl:template>
<xsl:template match="slice">
<tr>
<td><xsl:value-of select="@name"/></td>
<xsl:apply-templates/>
</tr>
</xsl:template>
<xsl:template match="value">
<td><xsl:value-of select="."/></td>
</xsl:template>
</xsl:stylesheet>
<table>
<tr>
<th></th>
<th>a</th>
<th>b</th>
<th>c</th>
<th>d</th>
<th>e</th>
</tr>
<tr>
<td>TERM1</td>
<td>23</td>
<td>2342</td>
<td>0.099</td>
<td>0.09</td>
<td>0.0730</td>
</tr>
<tr>
<td>TERM2</td>
<td>0.0655</td>
<td>0.099</td>
<td>0.002</td>
<td>0.015</td>
<td>0.099</td>
</tr>
</table>