tags:

views:

270

answers:

3

Is there any way to copy (deep) element from one DOMDocument instance to another?

<Document1>
  <items>
    <item>1</item>
    <item>2</item>
    ...
  </items>
</Document1>

<Document2>
  <items>
  </items>
</Document>

I need to copy /Document1/items/* to /Document2/items/.

It seems that DOMDocument doesn't have methods to import nodes from another DOMDocument. It even can't create nodes from xml text.

Of course I can achieve this using string operations, but maybe there is simpler solution?

+2  A: 

You can use the cloneNode method and pass a true parameter. The parameter indicates whether to recursively clone all child nodes of the referenced node.

Kirtan
Thanks. That worked perfectly, I didn't thought it would allow me to copy elements from one document to another :)
begray
A: 

In Java:

void copy(Element parent, Element elementToCopy)
{
   Element newElement;

   // create a deep clone for the target document:
   newElement = (Element) parent.getOwnerDocument().importNode(elementToCopy, true);

   parent.appendChild(newElement);
}
Dewin Cymraeg
A: 

the following function will copy a Document and preserve a basic <!DOCTYPE>, which is not true of the use of Transformer.

 public static Document copyDocument(Document input) {
        DocumentType oldDocType = input.getDoctype();
        DocumentType newDocType = null;
        Document newDoc;
        String oldNamespaceUri = input.getDocumentElement().getNamespaceURI();
        if (oldDocType != null) {
            // cloning doctypes is 'implementation dependent'
            String oldDocTypeName = oldDocType.getName();
            newDocType = input.getImplementation().createDocumentType(oldDocTypeName,
                                                                      oldDocType.getPublicId(),
                                                                      oldDocType.getSystemId());
            newDoc = input.getImplementation().createDocument(oldNamespaceUri, oldDocTypeName,
                                                              newDocType);
        } else {
            newDoc = input.getImplementation().createDocument(oldNamespaceUri,
                                                              input.getDocumentElement().getNodeName(),
                                                              null);
        }
        Element newDocElement = (Element)newDoc.importNode(input.getDocumentElement(), true);
        newDoc.replaceChild(newDocElement, newDoc.getDocumentElement());
        return newDoc;
    }
bmargulies