Dom Create Nodes in XML
How to Create Nodes in XML DOM
Creating nodes in an XML DOM means building new elements, text, or attributes programmatically, which you can later insert into the XML document tree.
Key Methods to Create Nodes
| Method | Description |
|---|---|
createElement(tagName) | Creates a new element node |
createTextNode(text) | Creates a new text node |
createAttribute(name) | Creates a new attribute node (less common, usually setAttribute used) |
Example: Create New XML Elements and Text Nodes
// Assume xmlDoc is your XML Document object// Create a new element <publisher>const publisher = xmlDoc.createElement("publisher");// Create a text node inside <publisher>const publisherName = xmlDoc.createTextNode("O'Reilly Media");// Append the text node to <publisher>publisher.appendChild(publisherName);// Now publisher element is: <publisher>O'Reilly Media</publisher>Complete Example: Creating and Adding Nodes
Suppose you want to create this XML snippet dynamically:
<publisher>O'Reilly Media</publisher>And add it inside a <book> element.
const book = xmlDoc.getElementsByTagName("book")[0];// Create <publisher> elementconst publisher = xmlDoc.createElement("publisher");// Create text node for publisher nameconst publisherText = xmlDoc.createTextNode("O'Reilly Media");// Append text to <publisher>publisher.appendChild(publisherText);// Append <publisher> inside <book>book.appendChild(publisher);Full HTML + JS Example Creating Nodes
<!DOCTYPE html><html><head><title>DOM Create Nodes in XML</title></head><body><h2>Create Nodes in XML DOM</h2><button onclick="createPublisher()">Add Publisher</button><pre id="xmlOutput"></pre><script>const xmlString = `<book id="101"> <title>Effective Java</title> <author>Joshua Bloch</author></book>`;const parser = new DOMParser();const xmlDoc = parser.parseFromString(xmlString, "text/xml");function displayXML() { const serializer = new XMLSerializer(); const xmlStr = serializer.serializeToString(xmlDoc); document.getElementById("xmlOutput").textContent = xmlStr;}function createPublisher() { const book = xmlDoc.getElementsByTagName("book")[0]; const publisher = xmlDoc.createElement("publisher"); const text = xmlDoc.createTextNode("O'Reilly Media"); publisher.appendChild(text); book.appendChild(publisher); displayXML();}displayXML();</script></body></html>Summary
Use
createElement()to make new tags.Use
createTextNode()to add text inside elements.Use
appendChild()to insert the created nodes into the XML tree.
Want me to help you with removing or replacing nodes next?