« April 22, 2008 | Main | May 16, 2008 »

May 7, 2008 Archives

May 7, 2008

Interesting XSLT Recipe - Computing line totals

You might have run into a requirement where you need to compute the total value of all items in a purchase order. Consider the PO XML shown below.





  1.   
  2. <?xml version="1.0" encoding="UTF-8" ?>  
  3. <po xmlns="http://www.example.org">  
  4.    <Items>  
  5.       <item>  
  6.          <price>1</price>  
  7.          <qty>2</qty>  
  8.       </item>  
  9.       <item>  
  10.          <price>3</price>  
  11.          <qty>4</qty>  
  12.       </item>  
  13.       <item>  
  14.          <price>5</price>  
  15.          <qty>6</qty>  
  16.       </item>  
  17.    </Items>  
  18. </po>  
You might want to compute the total value of all items in the purchase Order. For computing this, you would need to multiply the price and qty for each item, and add them up. In XSLT 1.0, I guess the way to do this would be to recursively invoke a template that computes the sum total. In XSLT 2.0, this can be done in a very elegant single expression.




  1.   
  2.   <xsl:variable name="itemVar" select="/tns:po/tns:Items/tns:item"/>                
  3.   <xsl:template match="/">  
  4.     <tns:poSummary>  
  5.       <tns:totalValue><xsl:value-of select="sum(for $i in $itemVar return ($i/tns:price * $i/tns:qty))"/></tns:totalValue>  
  6.     </tns:poSummary>  
  7.   </xsl:template>  
  8. </xsl:stylesheet>  

About May 2008

This page contains all entries posted to Ramkumar Menon's Blog in May 2008. They are listed from oldest to newest.

April 22, 2008 is the previous archive.

May 16, 2008 is the next archive.

Many more can be found on the main index page or by looking through the archives.

Powered by
Movable Type and Oracle