读书人

XSLT转换的有关问题

发布时间: 2012-02-11 09:51:34 作者: rapoo

XSLT转换的问题
XML内容如下:
<?xml version= "1.0 " encoding= "UTF-8 "?>
<?xml-stylesheet type= "text/xsl " href= "1.xsl "?>
<root>
<customer>
<name> Neo </name>
<amount> 20 </amount>
<description> amount using calculation 1 </description>
</customer>
<customer>
<name> Neo </name>
<amount> 40 </amount>
<description> amount using calculation 2 </description>
</customer>
</root>

想要转成HTML,用以下XSLT:
<?xml version= "1.0 " encoding= "UTF-8 "?>
<xsl:stylesheet xmlns:xsl= "http://www.w3.org/TR/WD-xsl ">
<xsl:template match= "/ ">
<html>
<head>
<title> Result </title>
</head>
<body>
<table>
<xsl:for-each select= "root/customer ">
<tr>
<td>
<xsl:value-of select= "name "/>
</td>
<td>
<xsl:value-of select= "amount "/>
</td>
<td>
<xsl:value-of select= "description "/>
</td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

结果customer重复了两次:
Neo 20 amount using calculation 1
Neo 40 amount using calculation 2

我知道如果amout和description是customer的子节点就没这问题了,但数据内容是别人的程序生成的,没办法,请各位帮忙想个办法,我希望输出是这样:

Neo
20 amount using calculation 1
40 amount using calculation 2


[解决办法]
<xsl:template match= "/ ">
<html>
<head>
<title> Result </title>
</head>
<body>
<table>
<xsl:for-each select= "root/customer ">
<xsl:if test= "not(preceding-sibling::customer[name=current()/name]) ">
<tr>
<xsl:apply-templates select= "name "/>
</tr>
<xsl:for-each select= "../customer[name=current()/name] ">
<tr>
<xsl:apply-templates select= "amount "/>
<xsl:apply-templates select= "description "/>
</tr>
</xsl:for-each>
</xsl:if>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
<xsl:template match= "amount|description|name ">
<td>
<xsl:value-of select= ". "/>
</td>
</xsl:template>

读书人网 >XML SOAP

热点推荐