Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Using the XSLT sum function (See related posts)

This XML and XSLT code is an example of storing and displaying a car mileage log. Notably the XSLT sum() function displays the total no of miles.


file: car_log.xsl
<?xml version="1.0"?>

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
      
    <xsl:template match="car_log">
      <div>      
        <p>Total miles this month: <xsl:value-of select="sum(records/entry/miles)" /></p>
        <xsl:apply-templates select="records"/>
      </div>
    </xsl:template>
    
    <xsl:template match="car_log/records/entry"><xsl:variable name="pos" select="position()"/>
    <div class="record">
      <dl>
        <dt><label for="trip"><xsl:value-of select="@title"/>trip</label></dt>
        <dd>
          <input type="text" id="trip{$pos}" name="trip{$pos}" value="{trip}" size="{@size}" />
        </dd>
          
        <dt><label for="miles"><xsl:value-of select="@title"/>miles</label></dt>
        <dd>
          <input type="text" id="miles{$pos}" name="miles{$pos}" value="{miles}" size="2" />
        </dd>
          
        <dt><label for="description"><xsl:value-of select="@title"/>description</label></dt>
        <dd>
          <input type="text" id="description{$pos}" name="description{$pos}" value="{description}"  />
        </dd>        
      </dl>
    </div>
    </xsl:template>
    </xsl:stylesheet>

file: car_log.xml
<car_log>
  <summary>
    <project>car_log</project>
  </summary>
  <records>
    <entry id='17962'><date>Wed Dec 12 20:00:33 +0000 2007</date><trip>trip to the supermarket</trip><miles>11.8</miles><description>my first trip with the GPS installed</description></entry>
    <entry id='18024'><date>Fri Dec 14 11:45:09 +0000 2007</date><trip>driving around the park</trip><miles>26.1</miles><description/></entry>
    <entry id='18173'><date>Thu Dec 20 01:21:27 +0000 2007</date><trip>trip to the supermarket</trip><miles> 8.5</miles><description/></entry>
    <entry id='18174'><date>Thu Dec 20 01:34:26 +0000 2007</date><trip>visiting parents</trip><miles>12.7</miles><description/>
    </entry>
  </records>
</car_log>

output
Total miles this month: 59.1
...

You need to create an account or log in to post comments to this site.


Click here to browse all 4857 code snippets

Related Posts