XML DOM Clone Nodes

To create a copy of a specified node, we use the cloneNode() method. The parameter of the cloneNode() method can either be true or false, thus indicating if all the attributes and child nodes of the original node should be included in the cloned node or not.

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, cloneNode, i, xmlDoc, txt;
    xmlDoc = xml.responseXML;
    txt = "";
    x = xmlDoc.getElementsByTagName('book')[1];
    cloneNode = x.cloneNode(true);
    xmlDoc.documentElement.appendChild(cloneNode);
 
    // Output all titles
    y = xmlDoc.getElementsByTagName("title");
    for (i = 0; i < y.length; i++) { 
        txt += y[i].childNodes[0].nodeValue + "<br>";
    }
    document.getElementById("hello").innerHTML = txt; 
}
</script>
 
</body>
</html>

Explanation:

In the above example, we are loading the “books.xml” in the xmlDoc to get the old node copied. It means that we will clone the second <book> node into “newNode”, to append the new node to the root node of the XML document.

Please Share