2009-04-20 2 views
1

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

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

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

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

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

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

ответ

3

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

+0

Спасибо. Это сработало отлично, я не думал, что это позволит мне копировать элементы из одного документа в другой :) – begray

0

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

следующая функция будет копировать документ и сохранить основную <!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; 
    } 
Смежные вопросы