TExcelTAD
Home › XML › DOM Create Nodes

XML DOM Create Nodes

To add new content to an XML document you first create the nodes, then insert them (next lesson). Every creation method lives on the document object — a node always belongs to a particular document, its ownerDocument.

Creation methods

Method Creates
xmlDoc.createElement('name') An element
xmlDoc.createElementNS(uri, 'prefix:name') An element in a namespace
xmlDoc.createTextNode('text') A text node
xmlDoc.createCDATASection('text') A CDATA section
xmlDoc.createComment('text') A comment
xmlDoc.createProcessingInstruction(target, data) A processing instruction
xmlDoc.createAttribute('name') An attribute node (rarely needed — use setAttribute)
document.implementation.createDocument(ns, rootName) A whole new XML document

A freshly created node is detached: it exists but isn't part of the tree until you insert it.

Creating an element with content

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const xmlDoc = new DOMParser().parseFromString('<library/>', 'application/xml');

    const book = xmlDoc.createElement('book');
    book.setAttribute('id', 'b4');

    const title = xmlDoc.createElement('title');
    title.appendChild(xmlDoc.createTextNode('Kindred'));   // explicit text node
    const author = xmlDoc.createElement('author');
    author.textContent = 'Octavia E. Butler';               // shortcut

    book.append(title, author);
    console.log('Connected before insert?', book.isConnected);

    xmlDoc.documentElement.appendChild(book);
    console.log('Connected after insert? ', book.isConnected);
    console.log(new XMLSerializer().serializeToString(xmlDoc));
  </script>
</body>
</html>

createTextNode and textContent produce the same result. textContent is shorter; createTextNode is useful when you need to insert text between other nodes.

A small helper

Creating nested elements one call at a time gets wordy. A tiny helper function makes it pleasant:

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const xmlDoc = document.implementation.createDocument(null, 'library');

    // el('book', {id: 'b5'}, el('title', {}, 'Beloved'), ...)
    function el(name, attrs = {}, ...children) {
      const e = xmlDoc.createElement(name);
      for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, v);
      e.append(...children);           // strings become text nodes
      return e;
    }

    xmlDoc.documentElement.append(
      el('book', { id: 'b5', genre: 'fiction' },
        el('title', {}, 'Beloved'),
        el('author', {}, 'Toni Morrison'),
        el('year', {}, '1987')),
      el('book', { id: 'b6', genre: 'science' },
        el('title', {}, 'The Selfish Gene'),
        el('author', {}, 'Richard Dawkins'),
        el('year', {}, '1976'))
    );
    console.log(new XMLSerializer().serializeToString(xmlDoc));
  </script>
</body>
</html>

Creating other node types

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const xmlDoc = document.implementation.createDocument(null, 'snippet');
    const root = xmlDoc.documentElement;

    root.setAttribute('language', 'js');
    root.appendChild(xmlDoc.createComment(' example code '));
    root.appendChild(xmlDoc.createCDATASection('if (a < b && b < c) { go(); }'));

    // A processing instruction before the root
    xmlDoc.insertBefore(xmlDoc.createProcessingInstruction('xml-stylesheet', 'type="text/css" href="code.css"'), root);

    console.log(new XMLSerializer().serializeToString(xmlDoc));
  </script>
</body>
</html>

Creating a new document from scratch

document.implementation.createDocument(namespaceURI, qualifiedName) gives you an empty XML document with a root element:

Call Result
createDocument(null, 'orders') <orders/>
createDocument('urn:shop', 'orders') <orders xmlns="urn:shop"/>
createDocument('urn:shop', 's:orders') <s:orders xmlns:s="urn:shop"/>

Note: In a namespaced document, create child elements with createElementNS using the same URI. Plain createElement in an XML document creates an element in no namespace, which serialises with xmlns="" to "escape" the default namespace — rarely what you want.

Element names are checked

Creation methods refuse invalid names, so you can't accidentally build a document that isn't well-formed:

js
try {
  xmlDoc.createElement('2nd item');
} catch (err) {
  console.log(err.name);   // InvalidCharacterError
}

Test yourself

Which object has the createElement method you need for an XML document?

  1. The parent element
  2. The XML document itself
  3. window
  4. XMLSerializer

Is a node created with createElement part of the document tree immediately?

  1. Yes, it is appended to the root
  2. No, it is detached until you insert it
  3. Only if it has text
  4. Only in HTML

What does document.implementation.createDocument(null, 'orders') produce?

  1. An HTML page
  2. An empty XML document with root <orders/>
  3. A text node
  4. An error