2013-03-07 152 views
1

我有一個XML1:插入XML文檔(JAVA)的另一個XML文檔的特定節點

<letterContent> 
    <key1>key1</key1> 
    <key2>key2</key2> 
    <type>456</type> 
    <object1>789</object1> 
    <effectiveDate>00</effectiveDate> 
    <expandedData /> 
</letterContent> 

...和XML 2:

<expandedData> 
    <rsnForReg> 
     <legacyTIN> 
      <asCurrent>leg123</asCurrent> 
     </legacyTIN> 
     <etpmTIN> 
      <asCurrent>etpm123</asCurrent> 
     </etpmTIN> 
     <regType> 
      <asCurrent/> 
     </regType> 
    </rsnForReg> 
</expandedData> 

我想插入XML 2使用JAVA在expandedData節點上創建XML 1文檔。

最終XML1應該是這樣的:

<letterContent> 
    <key1>key1</key1> 
    <key2>key2</key2> 
    <type>456</type> 
    <object1>789</object1> 
    <effectiveDate>00</effectiveDate> 
    <expandedData> 
     <rsnForReg> 
      <legacyTIN> 
       <asCurrent>leg123</asCurrent> 
      </legacyTIN> 
      <etpmTIN> 
       <asCurrent>etpm123</asCurrent> 
      </etpmTIN> 
      <regType> 
       <asCurrent/> 
      </regType> 
     </rsnForReg> 
    </expandedData> 
</letterContent> 

XML2插入XML1的expandedData節點上。有任何想法嗎?我知道我需要構建一個循環遍歷XML 2的遞歸函數,但不知道如何在java中實現它。

+0

[克隆dom.Document對象(http://stackoverflow.com/questions/5226852/cloning-dom-document-object) – hakre 2013-03-07 11:30:24

回答

1

考慮使用XPath

import static javax.xml.xpath.XPathConstants.*; 
import javax.xml.transform.TransformerFactory; 
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult; 
import javax.xml.xpath.*; 
import org.w3c.dom.*; 
import org.xml.sax.InputSource; 

public class Xml2into1 { 
    public static void main(String[] args) throws Exception { 
    // read from files 
    InputSource xml1 = new InputSource("xml1.xml"); 
    InputSource xml2 = new InputSource("xml2.xml"); 
    // find the node to add to 
    XPath xpath = XPathFactory.newInstance() 
     .newXPath(); 
    Node expandedData1 = (Node) xpath.evaluate("//expandedData", xml1, NODE); 
    Document doc1 = expandedData1.getOwnerDocument(); 
    // insert the nodes 
    Node expandedData2 = (Node) xpath.evaluate("//expandedData", xml2, NODE); 
    expandedData1.getParentNode() 
     .replaceChild(doc1.adoptNode(expandedData2), expandedData1); 
    // print results 
    TransformerFactory.newInstance() 
     .newTransformer() 
     .transform(new DOMSource(doc1), new StreamResult(System.out)); 
    } 
} 
+0

感謝的可能重複!這似乎工作得很好 – LeoBron 2013-03-11 12:35:52

相關問題