Wednesday, January 26, 2011

Power of XSLT

Just recently we changed the ERP system in the company I work for. Amongst other (more important) things the structure and format of product quotations has changed significantly.

The good news however was, that we finally had an XML export of those quotes.

It only took my 30 minutes to create an XSLT Template that would not only convert the XML to a really readable form (in HTML) but also add nifty features like totals per product type etc etc.

Quite frankly, it took me about 7 minutes to create the pure formatting XSLT and the remaining 23 minutes to figure out how to do sums in XSLT.

So, the two things I learned from this little exercise:

1. How to format a number using XSLT:

Use the format-number function as in:

<xsl:value-of select="format-number(amount, '#.00')"/>


2. How to add (sum) values (node-sets to be precise)

You have to use the sum function as in:

<xsl:value-of select="format-number(sum(//lineItem[@isSupportLine='true']/price), '#.00')"/>

For me this very line shows the power of XSLT:

It is adding all values of the "price" element of all "lineItems" that have an attribute "isSupportLine='true'".
In other words:  build the sum of the price of all support lines in the quote.

Or in SQL: select sum(price) from lineitems where isSupportLine="true"

No comments: