2011-01-06 6 views
5

다른 file2.xml에 file1.xml 요소를 삽입해야합니다. file2.xml에는 여러 개의 노드가 있고 각 노드에는 node_id가 있습니다. 그것을 할 수있는 방법이 있습니까?XML : xml 문서를 다른 문서의 노드에 추가하기

하자가 가정 :

file1.xml :

  < root> 
      <node_1>......</node_1> 
     </root> 

file2.xml :

  < root> 
      < node> 
       < node_id>1'<'/node_id> 
      < /node> 
     < /root> 

내가 원하는? file2.xml :

  < root> 
      < node> 
       <node_1>......</node_1> [here i want to append the file1.xml] 
      </node> 
     </root> 

답변

7
  1. file2의 모든 node_id 요소를 반복합니다.
  2. 각각에 대해 은 file1의 해당 node_x 요소 을 찾습니다.
  3. 다음 코드는이 보여 파일 2

에 파일 1에서 node_x을 추가

DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 

//build DOMs 
Document doc1 = builder.parse(new File("file1.xml")); 
Document doc2 = builder.parse(new File("file2.xml")); 

//get all node_ids from doc2 and iterate 
NodeList list = doc2.getElementsByTagName("node_id"); 
for(int i = 0 ; i< list.getLength() ; i++){ 

    Node n = list.item(i); 

    //extract the id 
    String id = n.getTextContent(); 

    //now get all node_id elements from doc1 
    NodeList list2 = doc1.getElementsByTagName("node_"+id); 
    for(int j = 0 ; j< list2.getLength() ; j++){ 

     Node m = list2.item(j); 

     //import them into doc2 
     Node imp = doc2.importNode(m,true); 
     n.getParent().appendChild(imp); 
    } 
} 

//write out the modified document to a new file 
TransformerFactory tFactory = TransformerFactory.newInstance(); 
Transformer transformer = tFactory.newTransformer(); 
Source source = new DOMSource(doc2); 
Result output = new StreamResult(new File("merged.xml")); 
transformer.transform(source, output);   

결과는 다음과 같습니다

<root> 
    <node> 
    <node_id>1</node_id> 
    <node_1>This is 1</node_1> 
    </node> 
    <node> 
    <node_id>2</node_id> 
    <node_2>This is 2</node_2> 
    </node> 
    <node> 
    <node_id>3</node_id> 
    <node_3>This is 3</node_3> 
    </node> 
</root> 
+0

오, 위대한 :) 나는 너에게 너무 감사한다. 이것은 내가 정확히 무엇을 찾고 있었는지입니다. – Bibhaw

+0

그러나 문서 importDocument 메서드가없는 것 같습니다 ... – tObi

2

일반적인 방법 :

번째 행의 첫 번째 문서에서 Document 개체 (SAXParser를, JDOM, DOM4J) 다음 오기 소자 <node_1>에 파일 1과 파일 2의 두 문서를 파싱 <node>에 추가하십시오. 그런 다음 해당하는 <node_id> 요소를 삭제하십시오.

을 가져 오는 것이 필요합니다. Document 구현은이 프로세스에 올바른 방법을 제공합니다. 한 문서의 요소를 다른 문서에 추가하면 DOMExceptions이됩니다.

+0

감사합니다 안드레아스,에 추가 할 수있는 방법이 node_id를 기준으로 node_id를 제거하지 않고 – Bibhaw

관련 문제