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.
-
- <?xml version="1.0" encoding="UTF-8" ?>
- <po xmlns="http://www.example.org">
- <Items>
- <item>
- <price>1</price>
- <qty>2</qty>
- </item>
- <item>
- <price>3</price>
- <qty>4</qty>
- </item>
- <item>
- <price>5</price>
- <qty>6</qty>
- </item>
- </Items>
- </po>
-
- <xsl:variable name="itemVar" select="/tns:po/tns:Items/tns:item"/>
- <xsl:template match="/">
- <tns:poSummary>
- <tns:totalValue><xsl:value-of select="sum(for $i in $itemVar return ($i/tns:price * $i/tns:qty))"/></tns:totalValue>
- </tns:poSummary>
- </xsl:template>
- </xsl:stylesheet>