• +43 660 1453541
  • contact@germaniumhq.com

Command Line Drawing on SVGs With XSLT 2.0


Command Line Drawing on SVGs With XSLT 2.0

If we want to post process images, one way to have basic post processing, is to just process the SVG file with XSLT. This is possible, since SVG images are just simple XML files. Let’s achieve that.

First we need an XSLT processor that handles XSLT 2.0. Unfortunately xsltproc doesn’t, but we have Saxon that handles it. Let’s install it:

sudo apt install libsaxon-java

Now that we have it, let’s create a basic XSLT file that simply draws a red line over the image, to show that the example is wrong. To achieve that, we’ll match on the SVG and just add the line:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:svg="http://www.w3.org/2000/svg" version="2.0">
    <xsl:output method="xml" encoding="utf-8" indent="yes"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <!-- We copy everything, and we add the tracing lines. -->
    <xsl:template match="svg:svg">
        <!-- we copy the svg, attributes, and child nodes -->
        <xsl:element name="svg" xmlns="http://www.w3.org/2000/svg">
            <xsl:copy-of select="@*" />
            <xsl:apply-templates select="node()"/>
            <xsl:element name="line"><!-- the new line -->
                <xsl:attribute name="x1">0</xsl:attribute>
                <xsl:attribute name="y1">0</xsl:attribute>
                <xsl:attribute name="x2">500</xsl:attribute>
                <xsl:attribute name="y2">500</xsl:attribute>
                <xsl:attribute name="style">stroke:rgb(255,0,0);stroke-width:2</xsl:attribute>
            </xsl:element>
        </xsl:element>
    </xsl:template>
</xsl:stylesheet>

We’ll save this as strike.xsl. Then let’s get an SVG, and just apply it.

Given we have this SVG:

Test SVG Image

When running the XSLT parser:

saxon-xslt test.svg strike.xsl > test2.svg

Then we get the processed SVG image:

Test SVG Image

Enjoy XSLT 2.0 with Saxon, and create something amazing :D!