How to Serialize an SVG DOM to an XML String
Serializing an in-memory SVG Document Object Model (DOM) subtree into
a standard XML string involves converting live DOM nodes into raw,
text-based XML markup. This process is essential for exporting
client-side graphics, saving SVGs to disk, or transferring vector markup
across network requests. In modern JavaScript environments, this is
primarily achieved using the built-in XMLSerializer
interface, ensuring that namespaces, attributes, and child nodes are
preserved correctly.
The Serialization Process
1. Identify or Create the SVG Subtree
The process begins with an in-memory reference to an
SVGElement (typically an <svg> root node
or a <g> group container). This element can either be
part of the active document or created dynamically via
document.createElementNS.
const svgElement = document.querySelector('svg');
// Or created in memory:
// const svgElement = document.createElementNS('http://www.w3.org/2000/svg', 'svg');2. Ensure Proper XML Namespaces
For an SVG to be valid as a standalone XML string, it must explicitly declare its XML namespace. If the in-memory element lacks this attribute, it should be appended before serialization:
if (!svgElement.getAttribute('xmlns')) {
svgElement.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
}
if (!svgElement.getAttribute('xmlns:xlink')) {
svgElement.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
}3. Instantiate the XMLSerializer
The browser provides the XMLSerializer API specifically
for converting DOM subtrees into XML markup. Instantiate the
serializer:
const serializer = new XMLSerializer();4. Execute
serializeToString()
Pass the root node of the SVG subtree to the
serializeToString() method. This traverses the DOM tree
depth-first, constructing an XML-compliant string representation of all
elements, attributes, and text nodes.
const svgString = serializer.serializeToString(svgElement);5. Format for Standalone Output (Optional)
If the serialized XML is intended for download or standalone file usage, prepend the standard XML declaration prolog:
const standaloneSvgString = '<?xml version="1.0" standalone="no"?>\r\n' + svgString;Non-Browser Environments (Node.js)
In server-side environments like Node.js where the native browser DOM
and XMLSerializer are unavailable, DOM simulation libraries
such as jsdom or XML manipulation tools provide identical
serialization behavior:
const { JSDOM } = require('jsdom');
const dom = new JSDOM(`<!DOCTYPE html><svg xmlns="http://www.w3.org/2000/svg"><circle cx="50" cy="50" r="40" /></svg>`);
const svgNode = dom.window.document.querySelector('svg');
const xmlString = new dom.window.XMLSerializer().serializeToString(svgNode);