XSLT to generate SVG tutorial
<pageby nominor="false" comments="false"/>
This article or section is currently under construction
In principle, someone is working on it and there should be a better version in a not so distant future.
If you want to modify this page, please discuss it with the person working on it (see the "history")
Introduction
This tutorial will teach you how to generate SVG graphics from XML data. We will produce both pure SVG and HTML5 embedded SVG.
Learning goals
- Understand the purpose of XSLT, i.e. be able to think of XSLT as a translation language.
- Do simple transformations from XML to HTML
- Be able to use simple XPath expressions (tag and attribute names) in template selectors and for element and attribute extraction.
- Prerequisites
- Editing XML (being able to use a simple DTD). Catch up with the Editing XML tutorial
- XML namespaces (some, have a look at the XML namespace article)
- HTML and CSS (some)
- XSLT Tutorial - Basics
- XPath tutorial - basics
- Static SVG tutorial (important)
- Using SVG with HTML5 tutorial
- SVG/SMIL animation tutorial (optional)
- Next steps
- XPath tutorial - basics
- XQuery tutorial - basics (if you have interest in XML databases)
- PHP - MySQL - XML tutorial - basics (shows how to display an XML result-set retrieved form MySQL with XSLT)
My first SVG from XML
Generating SVG with XSLT is really easy if you master some basic XSLT programming as explained in the XSLT Tutorial - Basics. Of course, you also should have some SVG basics.
At the time of writing, you can serve SVG in three different ways on the web:
- Embedded SVG in XHTML 1. This requires that you serve XHTML as XML. If you don't understand what that means, skip this option.
- Generate a pure SVG file. All modern browsers can display that.
- Generate an HTML5 file with inline SVG. All modern browsers can display that.
SVG Example level 0
We firstly will show how to produce some SVG graphic from the contents of a most simple XML document. We then show how to do this for HTML5.
Take the following XML file:
<?xml version="1.0" ?>
<?xml-stylesheet href="zero.xsl" type="text/xsl" ?>
<thing>
<height>50</height>
<width>100</width>
</thing>
We can imagine rendering this as a nice red rectangle. There we have to write a template that will extract contents of height and width and then use this to define the dimensions of the SVG rectangle. Absolute beginners should notice that the names of these XML tags do not matter, we also could have called these elements a and b...
Below is the XSLT code. As you can see, it is fairly straight forward. With respect to XSLT to HTML transforms, there are two differences:
- We should declare the SVG namespace in the xsl:stylesheet root element on top
- We should configure the output produced, else your browser may not want to display the SVG code.
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.w3.org/2000/svg"
>
<xsl:output
method="xml"
indent="yes"
standalone="no"
doctype-public="-//W3C//DTD SVG 1.1//EN"
doctype-system="http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"
media-type="image/svg" />
<xsl:template match="thing">
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" >
<rect x="10" y="10" width="{width}"
height="{height}" fill="red" stroke="black"/>
</svg>
</xsl:template>
</xsl:stylesheet>
Now let us examine the template that deals with thing. Since we do not use a template for the root //), we firstly must generate the svg tag.
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" >
.....
</svg>
Next, we simply have to define an SVG rectangle and substitute the values for width and height by the values that we extract from the XML. {width} and {height} will be substituted by text found within <width> and <height> tags in the XML document.
Live Code (may include slight variations):
HTML5 example level 0
Now let's produce HTML5. The principle is exactly the same, but the output declaration is a bit different and the template is longer since we will have to produced more code.
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.w3.org/2000/svg"
>
<xsl:output
method="xml"
doctype-system="about:legacy-compat"
omit-xml-declaration = "yes"
encoding="UTF-8"
indent="yes" />
<xsl:template match="thing">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8"></meta>
<title>XHTML5 + SVG example</title>
</head>
<body>
<p>This line is HTML, embedded SVG is below. Read the <a
href="http://edutechwiki.unige.ch/en/XSLT_to_generate_SVG_tutorial">
XSLT to generate SVG tutorial</a></p>
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" >
<rect x="10" y="10" width="{width}"
height="{height}" fill="red" stroke="black"/>
</svg>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Live Code (may include slight variations):
Creating a simple bar chart
The example we introduced above was really uninteresting. In XML data we usually find more than just two numbers. So let's see what we can do with a simple list of numbers:
Take the following xml file:
<?xml version="1.0" ?>
<?xml-stylesheet href="intro.xsl" type="text/xsl" ?>
<list>
<item>10</item>
<item>15</item>
<item>12</item>
<item>20</item>
<item>5</item>
</list>
Such a list would render nicely as a bar chart:
The following code will do that. Of course it remains simple. E.g. good code would also compute a height and width parameter that takes into account both the data and the drawing space we want to use.
The difference between the "zero" example and this one is that we do some very simple math and also that we use XSLT functions count() and position().
- The y coordinate of the rectangle is 100 minus the number found in the XML
y="{100- .}
- We use the count() function to figure out the number of item elements we got in the list.
<rect x="10" y="105" width="{10 * count(item)}"
height="5" fill="black" stroke="red"/>
- Please also note that empty spaces between elements do count as nodes according to the XML standard. Therefore you must remove these empty nodes with the following instruction.
<xsl:strip-space elements="list"/>
- Each rectangle is positioned in the SVG according to its position in the XML list:
<rect x="{10*position()}" y="{100- .}" width="10"
height="{.}" fill="red" stroke="black"/>
The full source code is below. We will not discuss the HTML5 version here, but below is link that will provide you code.
<?xml version="1.0"?>
<!-- keep all three namespaces, xlink may not be needed, but the others are -->
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns="http://www.w3.org/2000/svg"
>
<!-- **** output/input configuration -->
<xsl:output
method="xml"
indent="yes"
standalone="no"
doctype-public="-//W3C//DTD SVG 1.1//EN"
doctype-system="http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"
media-type="image/svg" />
<!-- must remove white spaces within the list element,
otherwise count will not work -->
<xsl:strip-space elements="list"/>
<xsl:template match="/">
<svg xmlns="http://www.w3.org/2000/svg" width="800" height="800" >
<xsl:apply-templates/>
</svg>
</xsl:template>
<xsl:template match="list">
<rect x="10" y="105" width="{10 * count(item)}"
height="5" fill="black" stroke="red"/>
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="item">
<rect x="{10*position()}" y="{100- .}" width="10"
height="{.}" fill="red" stroke="black"/>
</xsl:template>
</xsl:stylesheet>
Live example:
We also could procude a version for programmers who are scared of rule-based programming. You would use code like this:
<xsl:template match="list">
<xsl:for-each select="item">
<rect x="{10*position()}" y="{100- .}" width="10" height="{.}"
fill="red" stroke="black"/>
</xsl:for-each>
</xsl:template>
Live example:
Creating a flexible simple bar chart
The previous example has the flaw that height and width of the bars do not automatically adjust to
- Size of the SVG canevas
- Number of items
- Maxium value in an item
The result should look like the picture to the right. The bar chart should fill in the provided SVG drawing canevas. Of course we also want to be able to deal with any (reasonable) set of positive numbers, i.e. the XML file could include more or less items and also different values.
Firstly, we will allow users of this style-sheet to define the size of the canevas with XSLT variables
<!-- you could change these in any way you like -->
<xsl:variable name="svg_width" select="400"/>
<xsl:variable name="svg_height" select="300"/>
<xsl:variable name="padding" select="5"/>
This is one information we need to handle width, height and position of the bars. We then must figure out how many items we got. The next expression will compute the width of bar as the width of the SVG canevas - some padding divided by the number of items:
<!-- x-width with respect to N elements -->
<xsl:variable name="x_width"
select="($svg_width - 2*$padding) div count(//list/item)"/>
We also need some sort of "y-step" that multiplied with the number will define the height. That will depend on the largest number in the item set. Finding a maximum in XSLT 1.0 is a pain. Typically, for such problems, I would google for an answer and wind up taking a solution from a cool web site like stack overflow. The next expression will compute the width of bar:
<xsl:variable name ="y_steps">
<xsl:for-each select="//list/item">
<xsl:sort select="." data-type="number" order="descending"/>
<xsl:if test="position() = 1">
<xsl:value-of select="($svg_height - 2*$padding) div ."/>
</xsl:if>
</xsl:for-each>
</xsl:variable>
The rest is now fairly easy. We just show the template for item:
<xsl:template match="item">
<rect x="{$padding + $x_width * (position() - 1) }"
y="{($svg_height - $padding) - $y_steps * .}"
width="{$x_width}"
height="{. * $y_steps}"
fill="red" stroke="black"/>
</xsl:template>
Live example:
Work in progress
(some may just need documentation and or tuning ... other will not work)
... plus old stuff that I may fix
Current
Broken 12-year old stuff I may fix some day (project visualization)
- http://tecfa.unige.ch/guides/svg/ex/svg-xslt-visu/proj10-to-svg.xml
- http://tecfa.unige.ch/guides/svg/ex/svg-xslt-visu/proj10-to-svg.xml (fixed it a bit so that it displays)
Various (only 8 year old or so, sort of works ...)
Circles
Links
Tutorials
- How to turn an XML file into SVG using XSL?, StackOverflow Question/Answer, 2011.
Outdated tutorials
Links below point to texts that include useful information since they attempt more ambitious stuff. However, some portions are outdated, in particular complaints about bad SVG implementations and server-side instead of client-side use of XSLT. But XSLT coding itself looks just about fine to me, but then I am not an expert in either SVG or XSLT - Daniel K. Schneider (talk) 19:00, 20 March 2013 (CET)
- Using XSLT and SVG together: a survey of case studies by Max Froumentin, Vincent Hardy, W3C, W3C/Sun Microsystems Inc. (2004). I took some ideas from the introduction for my introduction.
- Using XML by J. David Eisenberg July 19, 2002 in AList Apart.
- XSLT pour SVG (in french)
- Hands-On SVG Tutorial Using XML and XSLT by Duane Odom
- Automated Tree Drawing: XSLT and SVG by by Jirka Kosek, September 08, 2004. This interesting article is only suitable for real programmers, since it includes string parsing code.
- Réaliser un histogramme en SVG (XSLT 1.0) by Emmanuel Lazinier (2001). A bar chart in french, but the code is fairly self-explaining ....
- Using XSLT to create SVG content from carto:net. I fixed the code a bit: xml, XSLT.
Good examples'
- extending SVG with XSLT
- For example: the 3D Pie Chart. If you like math, have a look at the XSLT code, if you know some math look at the simple bar chart and its stylesheet
- XSLorenz Lorenz Attractor fractal figure using only an XML document styled by an attached XSLT stylesheet, by Matt Gibson (2011).