Search code examples
svgxpathxml-namespacesxmlstarlet

xmlstarlet: insert svg fill attribute


I'm writing a batch file using xmlstarlet to create coloured versions of font awesome SVG files.

Here's an example input SVG file:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512">
    <path d="PATH DATA..."/>
</svg>

And I want to add a fill attribute to the path element.

However, my xmlstarlet command is not inserting a new fill attribute and I just get the formatted input file as output:

xmlstarlet ed -i 'svg/path' -t 'attr' -n 'fill' -v 'purple' input_file.svg

Any ideas welcome. Thanks!


Solution

  • With xmlstarlet and use of namespace:

    xmlstarlet edit --omit-decl \
                    -N x=http://www.w3.org/2000/svg \
                    --insert '//x:svg/x:path' -t attr -n "fill" -v "#ffffff" file.xml
    

    Output:

    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512">
      <path d="PATH DATA ..." fill="#ffffff"/>
    </svg>
    

    See: xmlstarlet edit