Search code examples
xmlsvgxsltsaxon

How do I process a directory of SVG files with Saxon XSLT


I'm trying to process a directory full of SVG files using XSL-T. I currently have tried:

<?xml version="1.0"?>
<xsl:stylesheet version="2.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" doctype-public="-//W3C//DTD SVG 1.1//EN http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"/>
  <xsl:strip-space elements="*"/>

  <xsl:template name="main">
    <svg xmlns="http://www.w3.org/2000/svg">
      <defs/>
      <xsl:apply-templates select="collection(concat(resolve-uri('src/images'),'?select=*.svg;content-type=application/xml'))"/>
    </svg>
  </xsl:template>

  <xsl:template match="/">
    <xsl:message>root</xsl:message>
    <xsl:apply-templates select="svg"/>
  </xsl:template>

  <xsl:template match="svg">
    <xsl:message>svg</xsl:message>
    <xsl:attribute name="id"><xsl:value-of select="document-uri(/)"/></xsl:attribute>
    <xsl:attribute name="viewBox"><xsl:value-of select="@viewBox"/></xsl:attribute>
    <xsl:apply-templates select="path"/>
  </xsl:template>

  <xsl:template match="path">
    <xsl:message>path</xsl:message>
    <xsl:attribute name="d"><xsl:value-of select="@d"/></xsl:attribute>
    <xsl:apply-templates select="@*"/>
  </xsl:template>

  <xsl:template match="@fill">
    <xsl:message>@fill</xsl:message>
    <xsl:attribute name="fill"><xsl:value-of select="."/></xsl:attribute>
  </xsl:template>

</xsl:stylesheet>

Using this from the command line: java net.sf.saxon.Transform -it:main -xsl:"%XSL%\svg-sprite.xsl" -o:"%OUT%\sprite.svg"

But, when I run it on a directory containing 29 SVG files all I get is 29 roots printed out. For some reason the <xsl:apply-templates select="svg"/> doesn't appear to be working .

Does anyone know either how to fix this dilemma or at least how to figure out why it isn't applying the defined svg template?


Solution

  • Add xpath-default-namespace="http://www.w3.org/2000/svg" on the root element of your XSLT. Basically the SVG namespace, I hope I have remembered and typed that right.