2009-04-20 8 views
1

하나의 DOMDocument 인스턴스에서 다른 인스턴스로 (깊은) 요소를 복사하는 방법이 있습니까?하나의 DOMDocument에서 다른 요소로 복사

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

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

/Document1/items/*을/Document2/items /에 복사해야합니다.

DOMDocument에는 다른 DOMDocument에서 노드를 가져 오는 메소드가없는 것으로 보입니다. xml 텍스트에서 노드를 만들 수도 없습니다.

물론 문자열 연산을 사용하여이 작업을 수행 할 수 있지만 더 간단한 해결책이 있을까요?

답변

3

cloneNode 메서드를 사용하고 true 매개 변수를 전달할 수 있습니다. 매개 변수는 참조 된 노드의 모든 자식 노드를 반복적으로 복제할지 여부를 나타냅니다. 자바에서

+0

감사합니다. 그것은 완벽하게 작동했는데, 한 문서에서 다른 문서로 요소를 복사 할 수 있다고 생각하지 않았습니다. :) – begray

0

:

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

다음 함수는 문서를 복사 Transformer의 사용 사실이 아니다 기본 <!DOCTYPE>을 보존합니다.

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; 
    } 
관련 문제