Search code examples
xmlnamespacesxmlstarletxmllint

Add a namespace prefix to the tags of the default name space of an XML document from the shell


I have a SVG file, which is an XML document:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:xlink="http://www.w3.org/1999/xlink"
   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape">
  <defs
     id="defs2">
  <!-- a lot of stuff --> </defs>
  <!-- more stuff like -->
  <metadata
     id="metadata5">
    <rdf:RDF>
      <cc:Work
         rdf:about="">
        <dc:format>image/svg+xml</dc:format>
        <dc:type
           rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
        <dc:title />
      </cc:Work>
    </rdf:RDF>
  </metadata>
  <!-- etc... -->
</svg>

I want to add the svg: prefix to all the tags corresponding to the default namespace in order to get next output:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg:svg
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns:xlink="http://www.w3.org/1999/xlink"
   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape">
  <svg:defs
     id="defs2">
  <!-- a lot of stuff--> </svg:defs>
  <!-- more stuff like -->
  <svg:metadata
     id="metadata5">
    <rdf:RDF>
      <cc:Work
         rdf:about="">
        <dc:format>image/svg+xml</dc:format>
        <dc:type
           rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
        <dc:title />
      </cc:Work>
    </rdf:RDF>
  </svg:metadata>
  <!-- etc... -->
</svg:svg>

I am sure this is possible in one or few command lines from the shell using xmllint and/or xmlstarlet but I can't manage it.


Solution

  • Are you prepared to give the new Gizmo tool in Saxon 10.0 a try? If so:

    Invoke Gizmo with a command like:

    java -cp saxon-he-10.0.jar:jline-2.9.jar net.sf.saxon.Gizmo
    

    Then enter the sub-commands

    load x/y/z/input.xml
    namespace svg http://www.w3.org/2000/svg
    rename /*:svg as "svg:svg"
    save x/y/z/output.xml
    quit
    

    Documentation is at http://www.saxonica.com/documentation/index.html#!gizmo

    Be aware that this is very new software (only released for the first time on Monday) so you're on the bleeding edge...