Search code examples
shellsvgxmlstarlet

Remove a node in an SVG by id using xmlstarlet


I have a folder with many SVGs in them. From all SVGs I need to remove a tag with a certain id. There are far too many files to do it by hand, so I have been working on a shell script to do that for me, but can't figure out how to use xmlstarlet to remove the tag.

For example, say we have foo.svg:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg">
  <g id="delete"/>
  <g id="keep"/>
</svg>

Then issuing the command: xmlstarlet ed -d "g[@id='delete']" foo.svg > bar.svg

would result it in:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg">
  <g id="keep"/>
</svg>

, but it doesn't. bar.foo still contains <g id="delete"/>.

Does anyone know the correct command to delete the <g id="delete"/> tag? Or any other tool I could use to batch precess the SVG files to get rid of the unwanted tag?

Cheers, Dominik


Solution

  • SVG uses namespaces, I think you will have to define them : documentation

    Then the correct syntax seems to be :
    xmlstarlet ed -N ns=http://www.w3.org/2000/svg -d "//ns:g[contains(@id,'delete')]" foo.svg > bar.svg