XML:将xml文档附加到另一个文档的节点中

Bib*_*haw 6 java xml

我必须将file1.xml元素插入另一个file2.xml.file2.xml有几个节点,每个节点都有node_id.有没有办法做到这一点.

让我们假设:

file1.xml:

         < root> 
            <node_1>......</node_1> 
         </root> 
Run Code Online (Sandbox Code Playgroud)

file2.xml:

         < root>
            < node>
               < node_id>1'<'/node_id>
            < /node>
         < /root> 
Run Code Online (Sandbox Code Playgroud)

我想要 ?file2.xml:

         < root>
            < node>
               <node_1>......</node_1> [here i want to append the file1.xml]
            </node>
         </root>
Run Code Online (Sandbox Code Playgroud)

dog*_*ane 8

  1. 迭代file2中的所有node_id元素.
  2. 对于每一个,在file1中查找相应的node_x元素.
  3. 将node_x从file1添加到file2中

以下代码说明了这一点:

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);        
Run Code Online (Sandbox Code Playgroud)

结果将是:

<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>
Run Code Online (Sandbox Code Playgroud)