如何用Javascript克隆XML文档?

时间:2022-10-30 09:37:24

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

在Javascript中克隆XML文档的最佳方式是什么?

I tried doing

我试着做

var newDocument = myDocument.cloneNode(true);

but that just returned null. I also considered doing

但它只返回null。我还考虑做

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.

但对于我的目的来说,这还不够,因为这样新的节点与以前具有相同的所有者文档。

1 个解决方案

#1


5  

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

您可以使用以下方法来克隆XML文档:

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);

#1


5  

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

您可以使用以下方法来克隆XML文档:

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);