[XML-SIG] Copying an element from one DOM to another

Fred L. Drake, Jr. fdrake@acm.org
Tue, 19 Feb 2002 15:15:32 -0500


Douglas Bates writes:
 > it.  I'm stuck on the "somehow copy it" part.  I had hoped to use
 > code like
 > 
 > output.documentElement.appendNode(input.elementOfInterest.cloneNode(1))
 > 
 > but that fails telling me
 > xml.dom.WrongDocumentErr: Node is from a different document
 > 
 > I could write a function that walked the tree of the source node and
 > created the copy in the target one element at a time but I have the
 > feeling that I must be missing something obvious.  Am I?

The DOM is weak when it comes to cross-document operations,
unfortunately.  DOM Level 3 helps a bit, but that has not been
finallized.

cloneNode() creates a copy, but the new node stays within the original
document.  importNode() is what you really want, and it was defined
for the DOM Level 2, but is not implemented in minidom (yet).
(minidom is, at the moment, more DOM Level 1 than DOM Level 2; I think
of this as a bug).  4DOM includes importNode().

You didn't tell how you were creating your DOM, but you should be able
to switch to 4DOM to get the importNode() method.  (Or, you may be
using 4DOM, in which case you just need to call it.)  You probably
want something like this:

    copy = output.importNode(input.elementOfInterest)
    output.documentElement.appendChild(copy)


  -Fred

-- 
Fred L. Drake, Jr.  <fdrake at acm.org>
PythonLabs at Zope Corporation