Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

XML DOM - Clone node


May 27, 2021 XML DOM


Table of contents


XML DOM clone node

By using the cloneNode() method, you can create a copy of the specified node, which is the clone node.

XML DOM - Clone node

Try it - instance

The following example uses the XML file .xml.
The function loadXMLDoc(), located in an external JavaScript, is used to load XML files.

Copy a node and append it to an existing node
This example uses cloneNode() to copy a node and append it to the root node of the XML document.


The replication node

The cloneNode() method creates a copy of the specified node.

The cloneNode() method has a parameter (true or false). This parameter indicates whether the cloned node includes all the properties and child nodes of the original node.

The following snippet copies the first node and appends it to the root node of the document:

xmlDoc=loadXMLDoc("books.xml");

oldNode=xmlDoc.getElementsByTagName('book')[0];
newNode=oldNode.cloneNode(true);
xmlDoc.documentElement.appendChild(newNode);

//Output all titles
y=xmlDoc.getElementsByTagName("title");
for (i=0;i<y.length;i++)
{
document.write(y[i].childNodes[0].nodeValue);
document.write("
");
}

Output:

Everyday Italian
Harry Potter
XQuery Kick Start
Learning XML
Everyday Italian

Try it out . . .

Example explanation:

  1. Use loadXMLDoc() to load .xml books" into xmlDoc
  2. Gets the node to replicate
  3. Use the cloneNode method to copy nodes to "newNode"
  4. Append a new node to the root node of the XML document
  5. Output all title for all books in the document
That's what's relevant to the DOM clone node, and until this section, the operation of the XML DOM node is much the same, starting with the next section, you'll learn about the use of related objects in the XML DOM.