Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I clone a XML document, in Javascript?

What is the best way to clone a XML document in Javascript?

I tried doing

var newDocument = myDocument.cloneNode(true);

but that just returned null. I also considered doing

var newNode = myDocument.documentElement.cloneNode(true);

but that is not enough for my purposes, since this way the new node has the same ownerDocument as before.

like image 617
hugomg Avatar asked Mar 14 '12 22:03

hugomg


People also ask

How do you clone an element in Javascript?

You call the cloneNode() method on the element you want to copy. If you want to also copy elements nested inside it, pass in true as an argument. // Get the element var elem = document. querySelector('#elem1'); // Create a copy of it var clone = elem.

What is clone node in Javascript?

The cloneNode() method of the Node interface returns a duplicate of the node on which this method was called. Its parameter controls if the subtree contained in a node is also cloned or not.

How do you duplicate an element in HTML?

The cloneNode() method creates a copy of a node, and returns the clone. The cloneNode() method clones all attributes and their values. Set the deep parameter to true if you also want to clone descendants (children).


1 Answers

You can do something like the following to clone a XML document:

var newDocument = oldDocument.implementation.createDocument(
    oldDocument.namespaceURI, //namespace to use
    null,                     //name of the root element (or for empty document)
    null                      //doctype (null for XML)
);
var newNode = newDocument.importNode(
    oldDocument.documentElement, //node to import
    true                         //clone its descendants
);
newDocument.appendChild(newNode);
  • createDocument documentation
  • importNode documentation
like image 124
matthewk Avatar answered Oct 20 '22 22:10

matthewk