Search code examples
svgsvg.js

How to store additional data in SVG?


I have a small editor that creates .svg files with diagrams (using svg.js).

The editor stores data about how the file created in its own simple text format, not unlike this one.

I would like to embed the source text directly in the SVG file, so I can load it back without losing any metainformation user specified (like comments and formatting).

What is the proper way to do that? The editor I linked above stores its data in the <source> tag right under <svg>. Is this a good and standards-compliant approach?

<svg 
  xmlns="http://www.w3.org/2000/svg" 
  width="445" height="319" 
  xmlns:xlink="http://www.w3.org/1999/xlink"
>
  <source><![CDATA[Andrew->China: Says Hello
  Note right of China: China thinks\nabout it
  China-->Andrew: How are you?
  Andrew->>China: I am good thanks!]]></source>
  <!-- SVG content here -->
</svg>

Solution

  • Create a custom namespace and store whatever you want under elements in that custom namespace. You can call the custom namespace element source if you want.

    Wrapping your custom content in a <metadata> tag is recommended in the SVG specification. Thanks to Alexander Gladysh for reminding me of that.