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
<!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:
<!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
<!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
createElementNSusing the same URI. PlaincreateElementin an XML document creates an element in no namespace, which serialises withxmlns=""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:
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?
- The parent element
- The XML document itself
windowXMLSerializer
Is a node created with createElement part of the document tree immediately?
- Yes, it is appended to the root
- No, it is detached until you insert it
- Only if it has text
- Only in HTML
What does document.implementation.createDocument(null, 'orders') produce?
- An HTML page
- An empty XML document with root
<orders/> - A text node
- An error