Generate SVG with XSLT

With XSLT, you can create and alter SVG documents on the fly.

Scalable Vector Graphics [Hack #66] provides an interoperable framework for creating graphics that, as XML documents, can be easily stored, transported, displayed in a web browser, and integrated into web pages and other applications. Two-dimensional line art, charts, and art of all kinds are possible with SVG. This hack will walk you through a simple business application using SVG and XSLT.

SVG isn’t always simple markup, but using XSLT you can use simple markup, separate from SVG, that can be transformed or merged into more complex SVG markup. For example, let’s say that your company regularly produces charts that reflect quarterly sales figures. You can keep the sales data in a small XML document and then integrate it into SVG with XSLT.

sales-2004Q2.xml (Example 3-45) is a brief document that expresses sales figures for the Eastern United States as a percentage of a $100,000 USD target.

Example 3-45. sales-2004Q2.xml

<?xml version="1.0" encoding="UTF-8"?>
   
<sales>
 <region>
  <title>Eastern Region Quarterly Sales (Second/'04)</title>
  <key1 area="New York Area">.95</key1>
  <key2 area="Virginia Area">.89</key2>
  <key3 area="Maryland Area">.67</key3>
  <key4 area="Connecticut Area">.65</key4>
  <key5 area="Delaware Area">.45</key5>
 </region>
</sales>

With XSLT, you can merge this data with an SVG document that produces a bar graph using the stylesheet bar.xsl (Example 3-46).

Example 3-46. bar.xsl

<xsl:stylesheet ...

Get XML Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.