Its a bit criminal how long its been since I worked with XSLT. I had this hellish project early in my programming career building a XML/XSLT program in ASP (yeah it was a while ago). I think it scarred me so bad I never had a desire to touch the stuff again. Really since you are able to read XML data straight into GridViews, there isn’t a whole lot of instances in my day to day coding life where I can’t just get by with that. Well today I had an issue where I was getting an XML datafeed from an affiliate provider and trying to find the best way to consume it. The big gotcha that kept me from going the easy GridView route was the format the data was in. It is ugly. The defining values are housed in the attributes and the node names are all the same (see below). What numbnuts designed this thing?
Anyway after trying to traverse the nodes, regenerate the XML document and other generally painful things to get the data to cooperate, I had a eureka moment to just plug it into an XSLT stylesheet. Talk about making my life incredibly easy. Here is the grand total of what it took to get the two elements plugged into my ASPX page. Notice the top 4 lines are my call to the affiliate site to get the XML dataset and line 5 is plugging the XML into the asp:XML control. Basically, one line of code. I like it.
Next, its time to dig into the XSLT. I've stripped this down to the essentials so we can focus on what is going on. Our xsl:for-each statement on line 15 drops down into the /response/result/hot node then our xsl:when tests to insure we bypass any test records the affiliate provider may have included. Next, we loop through the str node and pull out all of our relevant attributes (i.e. str[@name='description']). On line 41, we throw in our catchall for those datasets that come back without records.
All in all its pretty straight forward. I had lots of bells and whistles I had to incorporate to make this makeshift GridView work like it traditionally would under ASP.NET. Over the next few days, I'll post these extras.
Tags:
ASP.NET,
XML,
XSL,
xslt,
xsltransform