Malcolm Winslett


Using XSLT to generate a SVG

SVG (Scalable Vector Graphics) is an XML based markup language used to generate images. This step doesn’t require an extensive knowledge of SVG to understand. To start, we need a source XML file.

<?xml version="1.0" ?>
<?xml-stylesheet href="zero.xsl" type="text/xsl" ?>
<object>
  <height>150</height>
  <width>100</width>
</object>

To output SVG it is required to modify the doctype generated. The XSLT document is a bit different.

<?xml version="1.0"?>
 
<xsl:stylesheet version="2.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="object">
    <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>

The xsl namespace is declared. The SVG namespace is set. The output of the XSL document is set to xml and the doctype is set to SVG. The media-type corresponds to the mime type. The document then processes the XML file starting with object. Note that we can assign attribute values using curly braces with the name of the child elements without the use of the dollar sign like for variables.

To create a basic bar chart, we would use the for-each element.

<data>
    <item>15</item>
    <item>10</item>
    <item>5</item>
</data>

XSLT :

<?xml version="1.0"?>
 
<xsl:stylesheet version="2.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="data">
    <svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" >
    <xsl:for-each select="item">
      <rect x="{12 * position()}" y="{100 - .}" width="4" 
        height="{.}" fill="red" stroke="black"/>  
        </xsl:for-each>
    </svg>
  </xsl:template>
</xsl:stylesheet>

This creates 3 rectangles. New items introduced here are the position() function which is a numeric variable representing the current position of the for-each statement. We use it to move the rectangles along the X axis. The y={100-.} shows how to access the current node. The . means this item. It is used again for the height attribute. The data item value is subtracted from 100 for the y value since SVG starts at 0,0 and without defining the y coordinate the rectangles would be upside down.

Reference URL : http://edutechwiki.unige.ch/en/XSLT_to_generate_SVG_tutorial


Other XSLT posts ?