我有一个 XML,其中有一个带有标题、价格、作者、附加价格、艺术家、国家等属性的书籍列表。 XML 如下所示。
<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<additionalprice>12.90</additionalprice>
<year>1985</year>
</cd>
<cd>
<title>Hide your heart</title>
<artist>Bonnie Tyler</artist>
<country>UK</country>
<company>CBS Records</company>
<price>9.90</price>
<additionalprice>10.90</additionalprice>
<year>1988</year>
</cd>
等等
我想编写一个应用于 XML 的 XSLT 3.0 来获取 HTML。我想使用累加器来获取目录中的书籍总数。虽然有更好的方法,但我只是想使用累加器进行练习,并在包含标题、作者和总价的书籍的表格末尾打印总数。对于填写标题和作者,我使用了 for-each。总价=价格+附加价格。我想使用 iterate 来归档总价。任何人都可以帮我解决这个问题。我不完整的样式表如下所示:
<?xml version="3.0" encoding="UTF-8"?>
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="2">
<tr bgcolor="#9acd32">
<th style="text-align:left">Title</th>
<th style="text-align:left">Artist</th>
<th style="text-align:left">Total Price</th>
</tr>
<xsl:accumulator name="total" as="xs:integer" initial-value="0" streamable="no">
<xsl:accumulator-rule match="title" select="$value+1"/>
</xsl:accumulator>
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
<tr bgcolor="#FFA500">
<td> Total number of Books </td>
<td> <xsl:value-of select="accumulator-before('total')"/</td>
</tr>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
我不想使用流媒体。
如果您查看规范https://www.w3.org/TR/xslt-30/#accumulator-declaration,那么您会看到这xsl:accumulator
是一个声明,这意味着您必须将其用作xsl:stylesheet
, 不在模板内。
并且一个累加器值与一个节点相关联,函数如https://www.w3.org/TR/xslt-30/#func-accumulator-before "返回上下文节点处所选累加器的下降前值" 所以在你的情况下,你有一个带有上下文节点的模板,/
在值之前访问累加器没有多大意义,你更需要这个accumulator-after
值。
最后,您必须声明累加器将应用于默认模式
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:math="http://www.w3.org/2005/xpath-functions/math" exclude-result-prefixes="xs math"
version="3.0">
<xsl:mode use-accumulators="#all"/>
<xsl:accumulator name="total" as="xs:integer" initial-value="0" streamable="no">
<xsl:accumulator-rule match="title" select="$value + 1"/>
</xsl:accumulator>
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="2">
<tr bgcolor="#9acd32">
<th style="text-align:left">Title</th>
<th style="text-align:left">Artist</th>
<th style="text-align:left">Total Price</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td>
<xsl:value-of select="title"/>
</td>
<td>
<xsl:value-of select="artist"/>
</td>
</tr>
</xsl:for-each>
<tr bgcolor="#FFA500">
<td> Total number of Books </td>
<td>
<xsl:value-of select="accumulator-after('total')"/>
</td>
</tr>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句