Dom Add Nodes in XML
How to Add Nodes in XML DOM
You can add new elements, text, or attributes dynamically to an XML document using DOM methods in JavaScript.
Key Methods to Add Nodes
| Method | Purpose |
|---|---|
createElement(tagName) | Create a new element node |
createTextNode(text) | Create a new text node |
appendChild(node) | Add a child node to an element |
setAttribute(name, value) | Add or set an attribute to an element |
Example: Adding a New <book> Node to XML DOM
Assume you have this XML:
<library> <book id="101"> <title>Effective Java</title> <author>Joshua Bloch</author> </book></library>JavaScript to Add a New Book Node
// xmlDoc is your parsed XML document (XML DOM)const library = xmlDoc.getElementsByTagName("library")[0];// Create new <book> elementconst newBook = xmlDoc.createElement("book");newBook.setAttribute("id", "102");// Create and append <title>const title = xmlDoc.createElement("title");title.appendChild(xmlDoc.createTextNode("Clean Code"));newBook.appendChild(title);// Create and append <author>const author = xmlDoc.createElement("author");author.appendChild(xmlDoc.createTextNode("Robert C. Martin"));newBook.appendChild(author);// Append new <book> to <library>library.appendChild(newBook);// Now xmlDoc contains the new <book> nodeDisplay Updated XML (Optional)
To see the updated XML as a string:
const serializer = new XMLSerializer();const updatedXML = serializer.serializeToString(xmlDoc);console.log(updatedXML);Full HTML + JS Example Adding Nodes
<!DOCTYPE html><html><head><title>DOM Add Nodes in XML</title></head><body><h2>Books in Library</h2><button onclick="addBook()">Add New Book</button><pre id="xmlOutput"></pre><script>const xmlString = `<library> <book id="101"> <title>Effective Java</title> <author>Joshua Bloch</author> </book></library>`;const parser = new DOMParser();const xmlDoc = parser.parseFromString(xmlString, "text/xml");function displayXML() { const serializer = new XMLSerializer(); const str = serializer.serializeToString(xmlDoc); document.getElementById("xmlOutput").textContent = str;}function addBook() { const library = xmlDoc.getElementsByTagName("library")[0]; const newBook = xmlDoc.createElement("book"); newBook.setAttribute("id", "102"); const title = xmlDoc.createElement("title"); title.appendChild(xmlDoc.createTextNode("Clean Code")); newBook.appendChild(title); const author = xmlDoc.createElement("author"); author.appendChild(xmlDoc.createTextNode("Robert C. Martin")); newBook.appendChild(author); library.appendChild(newBook); displayXML();}// Display original XML at firstdisplayXML();</script></body></html>Summary
Use
createElementandcreateTextNodeto create nodes.Use
setAttributeto add attributes.Use
appendChildto attach nodes into the XML tree.Use
XMLSerializerto convert the DOM back to XML string.
Want me to show you how to remove or update nodes in XML DOM too?