XML DOM tutoria...login
XML DOM tutorial
author:php.cn  update time:2022-04-13 15:27:56

XML DOM clone node


XML DOM Clone Node


tryitimg.gifTry it - Example


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

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


Copy Node

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

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

The following code snippet copies the first <book> node and appends it to the root node of the document:

Example

<!DOCTYPE html>
<html>
<head>
<script src="loadxmldoc.js"> 
</script>
</head>
<body>

<script>
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName('book')[0];
cloneNode=x.cloneNode(true);
xmlDoc.documentElement.appendChild(cloneNode);

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

Run Example»

Click the "Run Example" button to view the online example

Explanation of the example:

  1. Use loadXMLDoc () Load "books.xml" into xmlDoc

  2. Get the node to be copied

  3. Use the cloneNode method to copy the node to "newNode "In

  4. Append a new node to the root node of the XML document

  5. Output all titles of all books in the document


php.cn