我想从XML文件中显示一组表,如下所示:
<reportStructure>
<table>
<headers>
<tableHeader>Header 1.1</tableHeader>
<tableHeader>Header 1.2</tableHeader>
</headers>
<tuples>
<tuple>
<tableCell>1.1.1</tableCell>
<tableCell>1.2.1</tableCell>
</tuple>
<tuple>
<tableCell>1.1.2</tableCell>
<tableCell>1.2.2</tableCell>
</tuple>
</tuples>
</table>
<table>
...
Run Code Online (Sandbox Code Playgroud)
我正在使用XSLT和XPath来转换数据,但是foreach并没有像我期望的那样工作:
<xsl:template match="reportStructure">
<xsl:for-each select="table">
<table>
<tr>
<xsl:apply-templates select="/reportStructure/table/headers"/>
</tr>
<xsl:apply-templates select="/reportStructure/table/tuples/tuple"/>
</table>
</xsl:for-each>
</xsl:template>
<xsl:template match="headers">
<xsl:for-each select="tableHeader">
<th>
<xsl:value-of select="." />
</th>
</xsl:for-each>
</xsl:template
<xsl:template match="tuple">
<tr>
<xsl:for-each select="tableCell">
<td>
<xsl:value-of select="." />
</td>
</xsl:for-each>
</tr>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)
虽然我希望每个table-tag输出一个表,但它会输出每个table-tag的所有表头和单元格.
您正在选择所有标题和元组apply-templates.
仅选择相关的:
<xsl:template match="reportStructure">
<xsl:for-each select="table">
<table>
<tr>
<xsl:apply-templates select="headers"/>
</tr>
<xsl:apply-templates select="tuples/tuple"/>
</table>
</xsl:for-each>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)
您还应该简单地将上述内容作为单个table模板,而不是xsl:for-each:
<xsl:template match="table">
<table>
<tr>
<xsl:apply-templates select="headers"/>
</tr>
<xsl:apply-templates select="tuples/tuple"/>
</table>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)