Posts tagged ‘xml’

Complex Sum in XSLT

When generating reports from XML data using XSLT I have to perform complex mathematical operations. Or, rather, operations that generic XPath can’t do. To achive that you can use variables in XSLT and fill node lists with them. So we have:

<xsl:variable name="totalCommission">
 <xsl:for-eachselect="orderz/accounts/payment/orderzs[@o_status != -9 and @o_prodtype != 'J']">
  <accum><xsl:value-of select="(@o_extprice  - @o_discount -itemmaster/itempricelist/@storecost*@qty) * ../../../../@salescommission div 100"/></accum>

as a result we create a variable that generates its element using some algorithm. After that, we can run a sum operation against it:

$<xsl:value-ofselect="format-number(sum(msxsl:node-set($totalCommission)/accum),'#,##0.00')" />

Very important in this operation is support of node set generator msxsl:node-set(), which is supported in MSXML that i use in this case.
To use it the root XML node will look like this:

<xsl:stylesheet xmlns:xsl=""version="1.0" xmlns:msxsl="urn:schemas-microsoft-com:xslt">

XML Cache

Developers frequently want to get data structures out of their code and into XML. But that bears a performance hit, since every time you read the file you have to parse it. In case of client applications you can avoid it by placing XML objects in the memory. However, in case of web-apps, memory gets destroyed after the request. Besides, you can’t monitor changes in the files themselves. ASP.NET introduced a very useful object called Cache, which is designed to help with precisely that problem. It stores objects on the application level (similar to Application object) but also allows you to monitor changes in the data. The following code is implementation of XmlDocument object storage and file change monitoring:

public static XmlDocument GetDOM(string path, Page page)
  if (page.Cache["xmlcache:dom:"+path] != null)
    return (XmlDocument)page.Cache["xmlcache:dom:"+path];
    XmlDocument x = new XmlDocument();
      x,new CacheDependency(page.MapPath(path)));
    return x;

The methods to store XslTransform and XPathDocument would look exactly the same. However, you should carefully monitor the contents of XslTransform document – CacheDependency object doesn’t monitor internal links of XSLT language, like xsl:import. By the way, I couldn’t find a way to automatically find all those tags in XSLT document and generate CacheDependancy for each of them.

Oh, and one other important thing. ASP.NET 2.0 extended on CacheDependency and introduced an object that monitors changes in SQL database! It’s ideal for many applications where you fill drop-downs with data from database, for example.