TExcelTAD
Home › XML › SVG as XML

SVG as XML

SVG (Scalable Vector Graphics) is an XML vocabulary for drawings. Every .svg file is an XML document, which means everything in this course applies to it: it must be well-formed, it uses a namespace, and you can parse it, query it with XPath, change it with the DOM and serialise it back.

An SVG file is XML

xml · try it yourself
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="120" viewBox="0 0 200 120">
  <title>Traffic light</title>
  <rect x="70" y="5" width="60" height="110" rx="10" fill="#333"/>
  <circle cx="100" cy="25" r="14" fill="#e53935"/>
  <circle cx="100" cy="60" r="14" fill="#555"/>
  <circle cx="100" cy="95" r="14" fill="#555"/>
</svg>

The playground shows its element tree. Notice the parts you already know from XML:

XML feature In this SVG
Root element <svg>
Default namespace xmlns="http://www.w3.org/2000/svg"
Empty elements <rect …/>, <circle …/>
Attributes for data cx, cy, r, fill
Text content <title> (also used as the accessible name)
Inside an HTML page, the HTML parser is forgiving about SVG. In a standalone .svg file, the XML rules apply — one unclosed tag and the image won't display at all.

Parsing SVG with DOMParser

Parse with the type image/svg+xml, then import the result into the page to draw it:

html · try it yourself
<!DOCTYPE html>
<html>
<body>
<div id="stage"></div>
<script>
const svgText = `<svg xmlns="http://www.w3.org/2000/svg" width="200" height="120">
<rect x="70" y="5" width="60" height="110" rx="10" fill="#333"/>
<circle id="red" cx="100" cy="25" r="14" fill="#e53935"/>
<circle id="amber" cx="100" cy="60" r="14" fill="#555"/>
<circle id="green" cx="100" cy="95" r="14" fill="#555"/>
</svg>`;
  const svgDoc = new DOMParser().parseFromString(svgText, 'image/svg+xml');
  if (svgDoc.querySelector('parsererror')) throw new Error('Bad SVG');

  console.log('root:', svgDoc.documentElement.localName, '| namespace:', svgDoc.documentElement.namespaceURI);
  console.log('circles:', svgDoc.getElementsByTagName('circle').length);

  const svg = document.importNode(svgDoc.documentElement, true);
  document.getElementById('stage').append(svg);

  // Cycle the lights with the DOM
  const order = ['red', 'green', 'amber'];
  const colours = { red: '#e53935', amber: '#fbc02d', green: '#43a047' };
  let i = 0;
  setInterval(() => {
    for (const id of order) svg.getElementById(id).setAttribute('fill', '#555');
    i = (i + 1) % order.length;
    svg.getElementById(order[i]).setAttribute('fill', colours[order[i]]);
  }, 1000);
</script>
</body>
</html>

Generating SVG from XML data

A classic use of XML skills: read data from one XML document, produce an SVG chart (another XML document). Here a bar chart is built with createElementNS and serialised:

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <div id="chart"></div>
  <script>
    const dataXml = `<rainfall city="Bergen" unit="mm">
      <month name="Jan">190</month><month name="Feb">152</month><month name="Mar">170</month>
      <month name="Apr">114</month><month name="May">106</month><month name="Jun">132</month>
    </rainfall>`;
    const data = new DOMParser().parseFromString(dataXml, 'application/xml');
    const months = [...data.querySelectorAll('month')].map(m => [m.getAttribute('name'), Number(m.textContent)]);

    const NS = 'http://www.w3.org/2000/svg';
    const svgDoc = document.implementation.createDocument(NS, 'svg');
    const svg = svgDoc.documentElement;
    svg.setAttribute('width', '260'); svg.setAttribute('height', '150');
    const max = Math.max(...months.map(m => m[1]));

    months.forEach(([name, mm], i) => {
      const h = Math.round(mm / max * 110);
      const bar = svgDoc.createElementNS(NS, 'rect');
      bar.setAttribute('x', 10 + i * 40); bar.setAttribute('y', 120 - h);
      bar.setAttribute('width', 30); bar.setAttribute('height', h);
      bar.setAttribute('fill', '#0060ac');
      const label = svgDoc.createElementNS(NS, 'text');
      label.setAttribute('x', 25 + i * 40); label.setAttribute('y', 138);
      label.setAttribute('text-anchor', 'middle'); label.setAttribute('font-size', '11');
      label.textContent = name;
      svg.append(bar, label);
    });

    const text = new XMLSerializer().serializeToString(svgDoc);
    document.getElementById('chart').innerHTML = text;   // safe: we generated it ourselves
    console.log(text.length, 'characters of SVG, starting:', text.slice(0, 60) + '…');
  </script>
</body>
</html>

The serialised string is a complete, standalone .svg file — you could offer it as a download.

Tip: When creating SVG elements from JavaScript, always use createElementNS('http://www.w3.org/2000/svg', …). Plain createElement('circle') makes an unknown HTML element that draws nothing.

XPath on SVG

Because SVG uses a default namespace, XPath needs a namespace resolver — the prefix s below is your own choice:

js
const resolver = (prefix) => prefix === 's' ? 'http://www.w3.org/2000/svg' : null;
const r = svgDoc.evaluate('count(//s:circle[@fill="#555"])', svgDoc, resolver, XPathResult.NUMBER_TYPE, null);
console.log(r.numberValue);   // 2 — the unlit lamps

Test yourself

Which MIME type tells DOMParser to parse SVG?

  1. text/svg
  2. image/svg+xml
  3. application/svg
  4. text/html

Why should SVG elements be created with createElementNS?

  1. It's faster
  2. So they are in the SVG namespace and actually render
  3. Because SVG has no namespace
  4. To add CSS classes