TExcelTAD
Home › XML › DOM Serializing

XML DOM Serializing

Serializing is the reverse of parsing: it turns a DOM tree back into XML text, ready to save, download, send to a server or display. In the browser this is the job of XMLSerializer.

text
   text ──DOMParser──► DOM tree ──(edit)──► DOM tree ──XMLSerializer──► text

serializeToString()

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const xmlDoc = new DOMParser().parseFromString(
      '<note><to>Kai</to><body>Back at 5</body></note>', 'application/xml');
    xmlDoc.querySelector('body').textContent = 'Back at 6 — sorry!';

    const s = new XMLSerializer();
    console.log('whole document:', s.serializeToString(xmlDoc));
    console.log('one element   :', s.serializeToString(xmlDoc.querySelector('to')));
  </script>
</body>
</html>

You can serialise a whole document or any single node — handy for logging or copying one fragment.

Escaping is automatic

The serializer converts special characters to entities so the output is always well-formed:

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const xmlDoc = document.implementation.createDocument(null, 'search');
    const q = xmlDoc.createElement('query');
    q.textContent = 'price < 10 & name = "Tom\'s"';
    q.setAttribute('label', 'A "quoted" <label> & more');
    xmlDoc.documentElement.appendChild(q);

    const out = new XMLSerializer().serializeToString(xmlDoc);
    console.log(out);

    // Round trip: parsing the output gives back the original values
    const back = new DOMParser().parseFromString(out, 'application/xml').querySelector('query');
    console.log('text survived :', back.textContent);
    console.log('attr survived :', back.getAttribute('label'));
  </script>
</body>
</html>

This is why you should never build XML by string concatenation with user data — the serializer gets the escaping right every time.

What the serializer does not do

Not (reliably) included How to get it
The XML declaration <?xml version="1.0"?> Prepend it yourself
Pretty-printing (indentation) Keep the original whitespace, or indent yourself
A specific attribute order or quote style Not controllable

Adding a declaration and indenting

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const xmlDoc = document.implementation.createDocument(null, 'library');
    for (const [id, title] of [['b1', 'The Hobbit'], ['b2', 'Dune']]) {
      const b = xmlDoc.createElement('book');
      b.setAttribute('id', id);
      const t = xmlDoc.createElement('title');
      t.textContent = title;
      b.appendChild(t);
      xmlDoc.documentElement.appendChild(b);
    }

    // Simple pretty-printer: insert newline + indentation text nodes before serializing
    function indent(node, level = 0) {
      const kids = [...node.children];
      if (kids.length === 0) return;
      for (const child of kids) {
        node.insertBefore(xmlDoc.createTextNode('\n' + '  '.repeat(level + 1)), child);
        indent(child, level + 1);
      }
      node.appendChild(xmlDoc.createTextNode('\n' + '  '.repeat(level)));
    }
    indent(xmlDoc.documentElement);

    const text = '<?xml version="1.0" encoding="UTF-8"?>\n' + new XMLSerializer().serializeToString(xmlDoc);
    console.log(text);
  </script>
</body>
</html>

Note: The indenting helper only works safely on data-style XML. In mixed content (text with inline elements), extra whitespace would change the meaning, so don't pretty-print documents like articles.

Saving the result

To let the user download the XML, wrap it in a Blob and use a temporary link:

js
const text = new XMLSerializer().serializeToString(xmlDoc);
const blob = new Blob([text], { type: 'application/xml' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = 'library.xml';
a.click();
URL.revokeObjectURL(a.href);

To send it to a server instead:

js
await fetch('/api/library', {
  method: 'PUT',
  headers: { 'Content-Type': 'application/xml' },
  body: new XMLSerializer().serializeToString(xmlDoc),
});

Serializing namespaces

The serializer adds any xmlns declarations needed so the output is namespace-correct, even if you built the tree with createElementNS:

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const SVG = 'http://www.w3.org/2000/svg';
    const doc = document.implementation.createDocument(SVG, 'svg');
    doc.documentElement.setAttribute('width', '40');
    const c = doc.createElementNS(SVG, 'circle');
    c.setAttribute('cx', '20'); c.setAttribute('cy', '20'); c.setAttribute('r', '15');
    doc.documentElement.appendChild(c);
    console.log(new XMLSerializer().serializeToString(doc));
  </script>
</body>
</html>

Test yourself

Which object turns a DOM tree back into XML text?

  1. DOMParser
  2. XMLSerializer
  3. JSON
  4. TextEncoder

If an element's text is a < b, how does the serializer write it?

  1. a < b
  2. a &lt; b
  3. <![CDATA[a < b]]>
  4. It throws an error

Does serializeToString(xmlDoc) include an XML declaration?

  1. Always
  2. You can't rely on it — add it yourself if you need one
  3. Only for SVG
  4. Only when the document has a DTD