XML DOM Add Nodes

We can add a child node to an existing node using the appendChild() method. The addition of the new node is done only after any existing child nodes. If we need to specify the position of the node, we can use the insertBefore() method.

Books.xml:

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
 
  <book category="Child">
    <title lang="en">ABC</title>
    <author>Author Name</author>
    <year>2020</year>
    <price>29.99</price>
  </book>
 
  <book category="Internet">
    <title lang="en">Basics</title>
    <author>Author 1</author>
    <author>Author 2</author>
 
 <year>2005</year>
    <price>49.99</price>
  </book>
 
</bookstore>

Example:

<!DOCTYPE html>
<html>
<body>
 
<p id="hello"></p>
 
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myFunction(this);
    }
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
 
function myFunction(xml) {
    var x, y, i, newElement, txt, xmlDoc;
    xmlDoc = xml.responseXML;
    newElement = xmlDoc.createElement("publisher");
    x = xmlDoc.getElementsByTagName("book")[0]
    x.appendChild(newElement);
 
   // Display all elements
    xlen = x.childNodes.length;
    y = x.firstChild;
    txt = "";
    for (i = 0; i < xlen; i++) {
        if (y.nodeType == 1) {
            txt += y.nodeName + "<br>";
        }
        y = y.nextSibling;
    }
    document.getElementById("hello").innerHTML = txt;
}
</script>
 
</body>
</html>

Output:

Explanation:

In the above example, we are creating the <publisher> element to add it after the last child of the first <book> element. Here, we will first load “books.xml” in the xmlDoc.

Example:

<!DOCTYPE html>
<html>
<body>
 
<p id="hello"></p>
 
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myFunction(this);
    }
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
 
function myFunction(xml) {
    var x, y, z, i, xLen, yLen, newEle, newText, xmlDoc, txt;
    xmlDoc = xml.responseXML;
    txt = "";
    x = xmlDoc.getElementsByTagName("book");
    xLen = x.length;
    for (i = 0; i < xLen; i++) { 
        newEle = xmlDoc.createElement("publisher");
        newText = xmlDoc.createTextNode("Publisher Name");
        newEle.appendChild(newText);
        x[i].appendChild(newEle);
    }
    // Output all titles and editions
    y = xmlDoc.getElementsByTagName("title");
    yLen = y.length
    z = xmlDoc.getElementsByTagName("publisher");
    for (i = 0; i < yLen; i++) { 
        txt +=  
        " - Publisher: " + 
        z[i].childNodes[0].nodeValue + "<br>";
    }
    document.getElementById("hello").innerHTML = txt; 
}
</script>
 
</body>
</html>

Output:

Explanation:

In the above example, we are creating the <publisher> element to add it after the last child of the first <book> element, but here the new element is added with a value. For this, we will first load “books.xml” in the xmlDoc before creating the node and a new text node “Publisher Name”. We will then append the text node to the <publisher> node and the <publisher> node to the <book> element.

Insert a Node – insertBefore() method:

To insert a node before a specified child node, the insertBefore() method is used, especially when the position of the added node is crucial.

Example:

<!DOCTYPE html>
<html>
<body>
 
<p id="hello"></p>
 
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myFunction(this);
    }
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
 
function myFunction(xml) {
    var xmlDoc = xml.responseXML;
    var newNode = xmlDoc.createElement("book");
    var x = xmlDoc.documentElement;
    var y = xmlDoc.getElementsByTagName("book");
    document.getElementById("hello").innerHTML =
    "Book elements before insert: " + y.length + "<br>";
 
    x.insertBefore(newNode, y[2]);
    document.getElementById("hello").innerHTML +=
    "Book elements after insert: " + y.length;
}
</script>
 
</body>
</html>

Output:

Explanation:

In the above example, we are loading “books.xml” in the xmlDoc. Here, we are creating a new element node <book> to be inserted in front of the last <book> element node. The new node will be added after the last existing child node, in case the second parameter of insertBefore() is null. To append a new child node to x, we are using x.insertBefore(newNode,null) and x.appendChild(newNode).

Add a New Attribute:

To set the value of an attribute, the setAttribute() method is used. In the absence of any method called add Attribute(), the setAttribute() takes the charge to create a new attribute if the attribute does not exist and to overwrite the existing value, if the attribute already exists.

Example:

<!DOCTYPE html>
<html>
<body>
 
<p id="hello"></p>
 
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myFunction(this);
    }
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
 
function myFunction(xml) {
    var xmlDoc = xml.responseXML;
    var x = xmlDoc.getElementsByTagName("title");
    x[0].setAttribute("publisher", "Publisher Name");
    document.getElementById("hello").innerHTML =
    "Publisher: " + x[0].getAttribute("publisher");
}
</script>
</body>
</html>

Output:

Explanation:

In the above example, we are loading “books.xml” in the xmlDoc. We will then set the value of the attribute “publisher” to “Publisher Name” for the first <book> element.

Add Text to a Text Node – insertData() method:

To insert data into an existing text node, the insertData() method is used. It has two parameters:

  • offset – It is used to specify where to begin inserting characters. The offset value starts at zero.
  • string – It is used to specify the string to insert.

Example:

<!DOCTYPE html>
<html>
<body>
 
<p id="hello"></p>
 
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myFunction(this);
    }
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
 
function myFunction(xml) {
    var x, txt, xmlDoc;
    xmlDoc = xml.responseXML;
    x = xmlDoc.getElementsByTagName("title")[0].childNodes[0];
    txt = x.nodeValue + "<br>";
    x.insertData(0,"Alphabet ");
    txt += x.nodeValue;
    document.getElementById("hello").innerHTML = txt;
}
</script>
 
</body>
</html>

Output:

Explanation:

In the above example, we are adding text to the text node of the first <title> element of books.xml.

Please Share