XML DOM - clone node
Try - Example
The following example uses XML files the Books.xml .
Function loadXMLDoc () , in an external JavaScript is used to load the XML file.
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.
Copy nodes
cloneNode () method creates a copy of the specified node.
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 fragment copies the first <book> node and appends it to the root node of the document:
Examples
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("
");
}
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
Harry Potter
XQuery Kick Start
Learning XML
Everyday Italian
try it"
Examples explain:
- Use loadXMLDoc () to " the Books.xml " into xmlDoc
- Get nodes to be copied
- Use cloneNode method to copy nodes to the "newNode" in
- Adding a new node to the root node of the XML document
- All output documents of title all book