Avinash Moharil

Subscribe to Avinash Moharil: eMailAlertsEmail Alerts
Get Avinash Moharil: homepageHomepage mobileMobile rssRSS facebookFacebook twitterTwitter linkedinLinkedIn

Related Topics: XML Magazine

XML: Article

Database-Driven Charting Using XSLT and SVG

Database-Driven Charting Using XSLT and SVG

Over the last few years, there have been significant developments in the XML world. Many enterprises have adopted XML for various purposes such as data transfer, reporting, client-tier presentation, server-to-server communication, and so on.

The need for representing data in XML form is greater than ever. Almost all database vendors have ways of extracting data in XML form. XML technology has enabled us to drive enterprise reports based on legacy databases. A previous article, "Using FOP for Industrial Needs" (XML-J, Vol.3, issue 10), discussed how to generate PDF reports based on XML data. Many times, reports are not complete without good graphical presentation. This article discusses how you can generate Scalable Vector Graphics (SVG) based on XML data. You can combine the FOP and SVG processes to generate complete reports.

Scalable Vector Graphics is a markup language for describing two-dimensional graphics in XML. It is a language for presenting rich graphical content, and it allows you to create graphics from XML data using XSLT. Most of the modern devices are raster-oriented, so it comes down to where graphics are rasterized - at the client or server level. SVG is rasterized at the client level, giving more flexibility for presenting graphics. SVG gives the user full control over the rasterization process. SVG documents define graphics as vector graphics rather than a bitmap so you can scale and zoom in and out without losing any detail or blurring the image.

SVG uses a "painters model" of rendering, meaning that paint is applied in successive operations to the output device such that each operation paints over some area of the output device. When the area overlaps a previously painted area, the new paint partially or completely obscures the old.

SVG 1.1, SVG 1.0, and SVG Mobile Profiles are W3C Recommendations. Work continues on SVG 1.2 and future profiles for mobile and printing. The complete Scalable Vector Graphics (SVG) 1.1 specification can be found at www.w3.org/TR/SVG11. A full list of implementations is available from the W3C pages at www.w3.org/Graphics/SVG/SVG-Implementations.htm8.

Why XSLT and SVG?
With the help of XSLT, XML data can be transformed into SVG graphics. SVG drawings can be dynamic and interactive, which gives tremendous flexibility when building data-dependent graphics such as charts. The Document Object Model (DOM) for SVG, which includes the full XML DOM, allows for straightforward and efficient vector graphics animation. A set of event handlers such as OnMouseover and OnClick can be assigned to any SVG graphical object. Because of the compatibility of SVG with other technologies, features like scripting can be built on SVG elements and other XML elements from different namespaces simultaneously within the same Web page.

Simple SVG Application
To understand how graphics are represented in SVG, let's look at the following simple SVG document that draws a rectangle. To view a stand-alone SVG, you need to download the SVG plug-in from www.adobe.com/svg. Once you have the plug-in installed you can view graphics from any SVG file with a .svg extension in a browser such as IE5 (see Listing 1).

When the document shown in Listing 1 is loaded in IE, you should see a red rectangle with a black border (see Figure 1).

SVG uses the namespace www.w3.org/2000/svg to distinguish between elements that are part of SVG and elements that are part of other markup languages.

The parent document element of an SVG document is an <svg> element. Children of this element are the other elements that are used to construct an image. In the example we're drawing a rectangle, a basic shape provided by SVG, using the <rect> element. The six basic shapes supported by SVG are <rect>, <circle>, <ellipse>, <line>, <polyline>, and <polygon>.

Putting It to Real Use
Before we jump into building a demo application, look at Table 1 to see the application areas in which we can use this technology.

Case Study
Let's look at a Sales Report for National Car Dealer, Inc., for quarterly sales of various vehicles sold in all four quarters of year 2002. Following are the sales figures for all the quarters:

  • Quarter 1 (Q1): $400,000
  • Quarter 2 (Q2): $600,000
  • Quarter 3 (Q3): $575,000
  • Quarter 4 (Q4): $800,000
In this case study we'll generate a dynamic bar chart based on the above facts. Let's assume that the data is stored in the database. This article does not delve into XML data file generation, but you can easily write a DataProcessingBean and have a simple getDataAsXML() method to achieve this. Alternatively, you can simply write a SQL query to return database data as XML.

There are three components needed to generate a dynamic SVG:

  • XML data file
  • XSLT stylesheet
  • SVG file
In addition, you'll have to download the Adobe SVG Viewer 3.0 and install it as a plug-in component for IE. XSLT is used to generate appropriate SVG elements to produce the bar chart graphic based on the dynamic data residing in an XML file. This would be the standard process for any enterprise graphic generation where enterprise data needs to be embedded in the SVG. You can simply double-click the SalesChart.svg file and IE will process it and display the graphic once you've installed the SVG viewer.

Figure 2 shows how our data processing looks.

XML data file
XML data can be generated using SQL commands (MS SQL and many other databases allow you to select rows as XML), or you can write simple Java components to generate XML files. Often, the XML data file will not represent a one-to-one relationship to the database table rows; rather, it will represent the processed data in an application tier (memory resident) based on various sources. Therefore, it is advisable to build a simple XML-generation Java object layer inside an application tier (see Listing 2).

The data shown in Listing 2 is in XML form and describes the Quarterly sales element that has elements for each quarter and the sales figures (in thousands) for each quarter. We'll use this data to draw a bar chart. The maximum sales amount in any quarter, as mentioned in our XML data file, is 900K. We can calculate this amount from data, but for our case study purpose we'll assume we have it in an XML data file.

XSLT stylesheet
XSLT is used to describe the structural transformation of XML. Generally, it is used in conjunction with XPath. XPath is used to address XML to select nodes for processing to define conditions for the way nodes will be processed and to generate text to be inserted in the resultant XML tree. In this case study the XML file is quite small and we select all of the nodes, but in a typical application you'd have a much more complex XML document to be processed using XSLT. As mentioned earlier, XPath can generate text to be inserted in the resultant XML tree. In this case the text to be inserted using XSLT is the SVG-specific text that would wrap the dynamic XML data and generate a well-formed resultant XML document that conforms to SVG specifications. As long as the resultant XML file is a valid SVG document, you can process it using an SVG viewer, such as one from Adobe, and generate the final graphic.

The main parts of our SalesChart XSLT document are:

  • Define SVG window properties
  • Define static graphic properties
  • Define dynamic graphic properties
Below are the parts of the SalesChart XSLT document that relate to the above points.

<!-- Size of the SVG window -->
<svg width="600" height="500">
. . .

SVG element attributes define graphic window width and height. We calculate the graphic properties using various elements such as <text>, <rect>, <line>, and <g>. Here we add header information, generate gray areas, and draw vertical and horizontal lines (see Listing 3).

The next step is building a dynamic graphic. We're trying to build a bar chart that reflects the quarterly sales figures. To draw the chart with relevant dimensions we need to consider the height of the tallest bar, the number of bars, the calibration of the Y-axis (bar height), and the spreading of bars evenly over the X-axis. These properties are very graphic-specific and will vary based on what you're trying to build. Nonetheless, this gives you an idea of how to build a dynamic graphic using SVG elements (see Listing 4).

Building this particular graphic is an iterative process. We start by matching the template on the root element (please see the complete code listing, available at www.sys-con.com/xml/sourcec.cfm). Then we iterate for each quarter by matching a template on the "Quarter" element. In the listing we're constructing a bar using a rectangle based on dimensions derived from quarterly figures.

The graphic is placed on the canvas using a coordinate system. The top left corner of the canvas is (0,0) point and the value increases as you move to the right or to the bottom. The bar height is calculated using the sales of each quarter. The maximum bar height for our graphics is 300 units. The maximum sales revenue for any quarter is $900K. We calculate the height of the bar for each quarter using the formula barHeight= ($sales/900) * 300 units. Based on the number of bars and the bar height we determine the X and Y positions for the vertical bars. The width of the bar is fixed at 40. The distance between the bars is fixed at 40. For example, we spare 100 units for the left margin and 40 units for space between the vertical axis and our first vertical bar. So the X coordinate on our coordinate system should be 140 - the equivalent of 140 units from the left border on canvas. We know that the Y coordinate for our X-axis is 400 as we have drawn a horizontal line from point (100,400) to point (500,400). In order to determine the Y coordinate of the left top corner of our bar rectangle, we need to subtract the height of the bar from 400. For our first bar using the above formula, the barHeight is 150, so we need to draw a rectangle with (X,Y) as (140,250), width 40 and height 150. Effectively, we are drawing a rectangle with points (140,250), (180,250), (140,400), (180,400). The bottom line of our bar rectangle merges on the X-axis. In order to write a label for our bar, we write "Q1" text just below our X-axis at (150,420). For drawing subsequent bars for other quarters we calculate the (X,Y) positions in a similar fashion.

SVG file
Once you process the above XSLT file on the input XML document, it produces an XML document that is also a well-formed SVG document (see Listing 5).

Figure 3 shows how the final graphic is displayed in IE when SalesChart.svg file is loaded in IE.

Advanced SVG Techniques
SVG supports the ability to change vector graphics over time. Animation has been very popular in electronic media. SVG's animation elements were developed in collaboration with the W3C Synchronized Multimedia (SYMM) Working Group, developers of the Synchronized Multimedia Integration Language (SMIL) 1.0 Specification. For detailed information about SVG animation and related elements, see the specification at www.w3.org/TR/SVG.

SVG can also be used in XSL-FO (Formatting Objects) to use graphics effectively in print media. Listing 6 demonstrates how you can include the above chart graphics in a PDF document.

The effective use of XSLT and SVG can help build dynamic and scalable graphics for data presentation. These technologies can be used to present raw XML data in more visual forms like charts and graphs for Web and print media. Since XML documents can be easily generated based on enterprise data, SVG becomes a truly dynamic graphic based on enterprise data.


  • Code for this article: www.sys-con.com/xml/sourcec.cfm
  • XSLT specifications: www.w3.org/TR/xslt
  • SVG specifications: www.w3.org/TR/SVG
  • XMLSPY: www.xmlspy.com
  • Adobe SVG viewer plug-in: www.adobe.com/svg
  • More Stories By Rajesh Zade

    Rajesh Zade has more than 13 years of experience in the computing field and has been working in various Java and e-Commerce technologies since 1996. He is currently chief technical architect for NetCliff, Inc., based in Santa Clara, CA.

    More Stories By Avinash Moharil

    Avinash Moharil has more than 14 years of experience in the computing field and has been working as a senior technology consultant and project manager in Silicon Valley.

    Comments (10) View Comments

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

    Most Recent Comments
    Rob Williamson 07/24/03 02:42:00 PM EDT

    Hi all,

    While bar charts are the best possible example for teaching people (I use them all the time). They are pretty simple apps that most enterprises have already mastered using other tools.

    If you want to do any very large complex SVG applications from data you *could be* looking at some very tedius XSLT coding and debugging.

    Here comes a product-ish pitch but Corel Smart Graphics Studio is an IDE that generates all this XSLT code for you when building complex data-driven applications; and yes you can open the code in notepad anytime you want (try that with binary compiled code).

    You can try it for free as well from a number of download sites (including the home page for corel of course).

    Sunitha 05/13/03 07:25:00 PM EDT

    This is a nice article explaining a new technology in an easy to understand language for beginners. I did not know about this technology till I read this article. This is great for GIS applications and many others. Since it supports XML, it might be great for applications for pocket pcs too.

    I have seen display of charts done on web pages using Flash and was wondering if I could get some information on some kind of comparision with Flash. On Searching in Google, I found this site which has some information on that which was very interesting to read.


    Mangesh Ralegankar 05/13/03 07:13:00 AM EDT

    Very good read on svg also reply to exciting technology makes it clear how it is diff from gif . here is also the link using the svg in the jsp web application.


    Palash Kundu 05/12/03 10:34:00 PM EDT

    Great Article explains in a very lucid manner all the related technical aspects.

    Sylvester Chesire 05/10/03 08:24:00 PM EDT

    This article clearly demonstrates the advantages of using

    Sylvester Chesire 05/10/03 08:23:00 PM EDT

    This article clearly demonstrates the advantages of using

    Jeetendra Jodhpurkar 05/07/03 10:17:00 PM EDT

    By all standards, certainly a very helpful write-up even for relatively 'non-to-low technical' professionals such as me! Thanks to the Dynamic Duo . . .

    Rajesh Zade 05/07/03 09:52:00 PM EDT

    SVG are much more advance than other graphic types such as gif. The main differences are:

    1. SVG documents define graphics as vector graphics rather than a bitmap so you can scale and zoom in and out without losing any detail or blurring the image.

    2. SVG uses a "painters model" of rendering, meaning that paint is applied in successive operations to the output device such that each operation paints over some area of the output device.

    Moreover, you have control over every bit (pixel) of the graphic via an XML document that defines it.


    U. N. Umesh 05/07/03 02:21:00 PM EDT

    Great article. The benefits are explained in easy to understand terms. We need more articles written along these lines so that the users can apply it to their work with minimal extra effort.

    Saurabh Bobde 05/07/03 02:17:00 PM EDT

    Very nice article, simplistically educating , for someone new to this technology.

    Have a Q - potentially, it appears that any kind of "graphic" can be generated as such. So, how does the resultant "graphic" compare with conventional .gif graphics? Does it replace it -- or its something completey different.