In pursuit of useful applications of SVG, I've become interested in using XSL transforms to turn data stored as XML into an SVG representation. I found a good starting article at A List Apart and it pointed to a great reference by Paul Grosso and Norman Walsh. These might be dated now, but I found them helpful starting points.
On to my example. We're going to need some data. I had a look at StatsCan and found a report on population by sex and age group. I would have liked to get some more complete raw data, but it appears to cost a few bucks, so I'll make do. I believe there are ways to scrape the data out of the table with just XSLT, but since this is a learning experience for me, I decided to skip that step by just pulling the numbers out by hand and creating an XML file with a text editor.
The results of my effort look a little like this:
The root node is called "populationbyageandsex" and each record (or row of data) is kept in a "recordbyagegroup". Between the open and close tags for "recordbyagegroup" are the fields for that record. Each field has a unique name and the content (between the open and close tags) of the element is the value of the field. The format is something I just made up for this example, XML is nice that way.
The next step was to write the XSL transformations that would understand the data well enough to create a chart in SVG.
At first I didn't understand that XSLT is a complete programming language (it may not have been at points in the past, but that's what it is now). I also didn't realize that XSLT is designed for transforming one flavour of XML to another. I guess I was just pretty confused by the whole thing (that's not to say that I'm not still a little muddy on the subject).
Here's what the XSLT looks like now that it works:
The xsl:value-of element does all the substitution in my example (there may be other and better ways, but I don't know them yet). The select attribute of the value-of tag can refer to several expressions. A tag in the current node like the places that use select="kpersons". A function from XPath like select="position()" (this gets the ordinal of the current node in a collection). A formula like select="$position * 100". Note that I did a bad thing here - I named a parameter "position" and I filled its value from the position() function. I realize this can be a little confusing, I'll fix it later. In the formula case, $position refers to the parameter position from the xsl:param name="position" line.
The plot-line template produces one line of the chart and a text label for it. It does this with the xsl:element tag. This tag inserts an element into the output. The attributes of the element are nested with xsl:attribute tags. There's not really too much more to it once you know that, but I'll go over some more details later. Oh, here's the SVG - you'll need an SVG viewer to display it.
Can't view SVG? There's an explanation of how to view SVG on SVGBasics.com.