XML DOM Cloning Nodes
Try it - Example
The following example uses the XML file books.xml.
function loadXMLDoc(), located in an external JavaScript, 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.
Cloning a 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 the attributes and child nodes of the original node.
The following code snippet copies the first
Example
xmlDoc
=
loadXMLDoc
(
"
books.xml
"
)
;
x
=
xmlDoc
.
getElementsByTagName
(
'
book
'
)
[
0
]
;
cloneNode
=
x
.
cloneNode
(
true
)
;
xmlDoc
.
documentElement
.
appendChild
(
cloneNode
)
;
//
Output the text values of all title nodes
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 »
Example explanation:
- Use loadXMLDoc() to load "books.xml" load into xmlDoc
- Get the node to copy
- Use the cloneNode method to copy the node into "newNode"
- Append the new node to the root node of the XML document
- Output all titles of all books in the document