Копировать элемент из одного DOMDocument в другой - PullRequest
1 голос
/ 20 апреля 2009

Есть ли способ скопировать (глубокий) элемент из одного экземпляра DOMDocument в другой?

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

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

Мне нужно скопировать / Document1 / items / * в /Document2/items/.

Кажется, что в DOMDocument нет методов для импорта узлов из другого DOMDocument. Он даже не может создавать узлы из XML-текста.

Конечно, я могу добиться этого с помощью строковых операций, но, может быть, есть более простое решение?

Ответы [ 3 ]

3 голосов
/ 20 апреля 2009

Вы можете использовать метод cloneNode и передать параметр true. Параметр указывает, следует ли рекурсивно клонировать все дочерние узлы ссылочного узла.

0 голосов
/ 06 августа 2010

следующая функция скопирует документ и сохранит базовый <!DOCTYPE>, что неверно при использовании 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;
    }
0 голосов
/ 20 ноября 2009

В 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);
}
...