我想创建1个XSL样式表,可以创建具有特定数据标题和列数的HTML表格代码。以下是我希望由1个样式表处理的两组示例数据
<root>
<row>
<postId>1</postId>
<id>1</id>
<name>name 1</name>
<email>email_1@gardner.biz</email>
<body>body 1</body>
</row>
<row>
<postId>1</postId>
<id>2</id>
<name>name 2</name>
<email>email_2@gardner.biz</email>
<body>body 2</body>
</row>
</root>
<root>
<row>
<id>1</id>
<desc>desc 1</desc>
<Note>Note 1</Note>
</row>
<row>
<id>2</id>
<desc>desc 2</desc>
<Note>Note 2</Note>
</row>
<row>
<id>3</id>
<desc>desc 3</desc>
<Note>Note 3</Note>
</row>
</root>
然后我希望表单产生如下输出:
<table>
<thead>
<th>postId</th><th>id</th><th>name</th><th>email</th><th>body</th>
</thead>
<tbody>
<tr>
<td>1</td><td>1</td><td>mane 1</td><td>email_1@gardner.biz</td><td>body 1</td>
</tr>
<tr>
<td>1</td><td>2</td><td>mane 2</td><td>email_2@gardner.biz</td><td>body 2</td>
</tr>
</tbody>
<table>
<thead>
<th>id</th><th>desc</th><th>Note</th>
</thead>
<tbody>
<tr>
<td>1</td><td>desc 1</td><td>Note 1</td>
</tr>
<tr>
<td>2</td><td>desc 2</td><td>Note 2</td>
</tr>
<tr>
<td>3</td><td>desc 3</td><td>Note 3</td>
</tr>
</tbody>
</table>
我已经找到了表头(见下文),但我似乎无法让身体发挥作用。我无法弄清楚如何显示一个元素的值,我不知道它的名称,甚至是否存在。
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="root">
<html>
<body>
<h2>My Table Data</h2>
<table border="1">
<thead>
<tr bgcolor="#9acd32">
<xsl:for-each select="row[1]/*">
<th><xsl:value-of select ="name(.)"/></th>
</xsl:for-each>
</tr>
</thead>
<tbody>
?????
</tbody>
答案 0 :(得分:1)
如果您的row
元素总是具有相同数量的元素,并且顺序相同,则您不必担心名称和您的?????可以简单地用这个代替......
<xsl:for-each select="row">
<tr>
<xsl:for-each select="*">
<td>
<xsl:value-of select="." />
</td>
</xsl:for-each>
</tr>
</xsl:for-each>
另一方面,如果row
元素可能具有不同顺序的元素,甚至丢失,那么(假设第一行始终完成),您可以定义一个包含“标题”行单元格的变量
<xsl:variable name="headers" select="row[1]/*"/>
然后你的????变成这个...
<xsl:for-each select="row">
<xsl:variable name="currentRow" select="."/>
<tr>
<xsl:for-each select="$headers">
<xsl:variable name="currentHeaderName" select="name()" />
<td>
<xsl:value-of select="$currentRow/*[name() = $currentHeaderName]"/>
</td>
</xsl:for-each>
</tr>
</xsl:for-each>
试试这个XSLT
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="root">
<html>
<body>
<h2>My Table Data</h2>
<xsl:variable name="headers" select="row[1]/*"/>
<table border="1">
<thead>
<tr bgcolor="#9acd32">
<xsl:for-each select="$headers">
<th>
<xsl:value-of select="name(.)"/>
</th>
</xsl:for-each>
</tr>
</thead>
<tbody>
<xsl:for-each select="row">
<xsl:variable name="currentRow" select="."/>
<tr>
<xsl:for-each select="$headers">
<xsl:variable name="currentHeaderName" select="name()" />
<td>
<xsl:value-of select="$currentRow/*[name() = $currentHeaderName]"/>
</td>
</xsl:for-each>
</tr>
</xsl:for-each>
</tbody>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>