XSLT summarize value

2019-02-27 10:58发布

问题:

I need to generate an item that accumulates a total for a given XML input.

The XML input is:

<catalog xmlns:foo="http://www.foo.org/" xmlns:bar="http://www.bar.org">
  <item id="1" amount="10" />
  <item id="2" amount="20" />           
</catalog>

This is my XSLT:

 <?xml version="1.0" encoding="ISO-8859-1"?>
  <xsl:stylesheet version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
  xmlns:foo="http://www.foo.org/" xmlns:bar="http://www.bar.org">
  <xsl:template match="/">
  <html>
 <body>
 <h2>My CD Collection</h2>
 <table border="1">
  <tr bgcolor="#9acd32">
    <th>Id</th>
    <th>Amount</th>     
  </tr>

  <xsl:for-each select="catalog/item">
  <tr>
    <td><xsl:value-of select="@id"/></td>
    <td><xsl:value-of select="@amount"/></td>   

  <br/>
   Total: 

  </tr>
  </xsl:for-each>

</table>

And this is my output:

<html xmlns:foo="http://www.foo.org/" xmlns:bar="http://www.bar.org">
<body>
  <h2></h2>
  <table border="1">
     <tr bgcolor="#9acd32">
        <th>Id</th>
        <th>Amount</th>
     </tr>
     <tr>
        <td>1</td>
        <td>10</td>
        <br/>
 Total: 

  </tr>
     <tr>
        <td>2</td>
        <td>20</td>
        <br/>
  Total: 

  </tr>
  </table>

The result should be Total = 30

How can I implement a sum function that returns the correct total value?

回答1:

Use the sum() function to total the @amount values:

<xsl:value-of select="sum(/catalog/item/@amount)"/>

Note that you'll want to move your Total: label along with the above xsl:value-of outside of your xsl:for-each loop.



标签: xml xslt xpath