xslt的新手很容易,我一直试图通过xslt将xml转换为html,我似乎无法正确使用它。
标题和行不应该是硬编码的,应该尽可能通用。
通缉结果:
Xml使用我无法控制
<?xml version="1.0" encoding="utf-8"?>
<Generated>
<Employees>
<Employee name="Joe Bloggs">
<Sales>
<Sale key="Sale-Id" value="333" />
<Sale key="Sale-Field1" value="a" />
<Sale key="Sale-Field2" value="b" />
</Sales>
</Employee>
<Employee name="Mark Bloggs">
<Sales>
<Sale key="Sale-Id" value="334" />
<Sale key="Sale-Field1" value="c" />
<Sale key="Sale-Field2" value="d" />
</Sales>
</Employee>
</Employees>
</Generated>
XSLT My Attempt
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" version="4" encoding="UTF-8" indent="no" omit-xml-declaration="yes"/>
<!-- main body -->
<xsl:template match="/">
<html>
<body>
<h3>Employees</h3>
<table border="1">
<tr bgcolor="blue">
<!--Header only so select first row to get headers-->
<xsl:for-each select="(Generated/Employees/Employee)[1]/Sales/Sale">
<th>
<xsl:value-of select="@key"/>
</th>
</xsl:for-each>
</tr>
<!--Get all the other rows-->
<xsl:for-each select="(Generated/Employees/Employee)/Sales/Sale">
<tr>
<td>
<xsl:value-of select="@value"/>
</td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
我的错误结果
任何建议如何修复此问题并根据上图
获取我想要的结果非常感谢
答案 0 :(得分:2)
以Martin Honnen's answer为基础(请接受他的回答)。
我想念的是如何得到这个名字。我需要另一个嵌套的foreach吗?以及如何?
无需额外for-each
。在第一行的开头引入另一个td
并将其命名为“Name”。然后,在每个for-each
元素的Employee
内,输出包含td
值的@name
元素。
XSLT样式表
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="html" encoding="UTF-8" indent="yes" omit-xml-declaration="yes"></xsl:output>
<xsl:template match="/">
<html>
<body>
<h3>Employees</h3>
<table border="1">
<tr bgcolor="blue">
<td>Name</td>
<xsl:for-each select="(Generated/Employees/Employee)[1]/Sales/Sale">
<th>
<xsl:value-of select="@key"></xsl:value-of>
</th>
</xsl:for-each>
</tr>
<xsl:for-each select="Generated/Employees/Employee">
<tr>
<td>
<xsl:value-of select="@name"></xsl:value-of>
</td>
<xsl:for-each select="Sales/Sale">
<td>
<xsl:value-of select="@value"></xsl:value-of>
</td>
</xsl:for-each>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
HTML输出
<html>
<body>
<h3>Employees</h3>
<table border="1">
<tr bgcolor="blue">
<td>Name</td>
<th>Sale-Id</th>
<th>Sale-Field1</th>
<th>Sale-Field2</th>
</tr>
<tr>
<td>Joe Bloggs</td>
<td>333</td>
<td>a</td>
<td>b</td>
</tr>
<tr>
<td>Mark Bloggs</td>
<td>334</td>
<td>c</td>
<td>d</td>
</tr>
</table>
</body>
</html>
呈现HTML
答案 1 :(得分:1)
更改
<xsl:for-each select="(Generated/Employees/Employee)/Sales/Sale">
<tr>
<td>
<xsl:value-of select="@value"/>
</td>
</tr>
</xsl:for-each>
到
<xsl:for-each select="Generated/Employees/Employee">
<tr>
<xsl:for-each select="Sales/Sale">
<td>
<xsl:value-of select="@value"/>
</td>
</xsl:for-each>
</tr>
</xsl:for-each>