title: Merging xml file using java NodeList
body: <p>I'm trying to merge two xml files as shown below but i can't able to get the desired output please help me thank you </p>
  
  <p>Java code:</p>
  
  <pre><code>DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();   
  domFactory.setIgnoringComments(true);  
  DocumentBuilder builder = domFactory.newDocumentBuilder();   
  Document doc = builder.parse(new File("file1.xml"));   
  Document doc1 = builder.parse(new File("file2.xml"));   
  
  NodeList nodes = doc.getElementsByTagName("staff");  
  
  NodeList nodes1 = doc1.getElementsByTagName("staff");
  
  for(int i=0;i&lt;nodes1.getLength();i=i+1){  
  
  Node n= (Node) doc.importNode(nodes1.item(i), true);  
  nodes.item(i).getParentNode().appendChild(n);
  
  }  
  
  Transformer transformer = TransformerFactory.newInstance().newTransformer();  
  transformer.setOutputProperty(OutputKeys.INDENT, "yes");  
  
  StreamResult result = new StreamResult(new StringWriter());  
  DOMSource source = new DOMSource(doc);  
  transformer.transform(source, result);  
  Writer output = null;
  output = new BufferedWriter(new FileWriter("mergedxml.xml"));
  
  String xmlOutput = result.getWriter().toString();  
  output.write(xmlOutput);
  output.close();
  System.out.println("merge complete");
  </code></pre>
  
  <p>File1.xml</p>
  
  <pre><code>    &lt;company&gt;
          &lt;staff&gt;
              &lt;name&gt;john&lt;/name&gt;
              &lt;phone&gt;465456433&lt;/phone&gt;
              &lt;email&gt;gmail1&lt;/email&gt;
          &lt;/staff&gt;
      &lt;/company&gt;
  </code></pre>
  
  <p>File2.xml</p>
  
  <pre><code>    &lt;company&gt;
          &lt;staff&gt;
              &lt;area&gt;area1&lt;/area&gt;
              &lt;city&gt;city1&lt;/city&gt;
          &lt;/staff&gt;
      &lt;/company&gt;
  </code></pre>
  
  <p>Current output:</p>
  
  <pre><code>    &lt;company&gt;
          &lt;staff&gt;
              &lt;name&gt;john&lt;/name&gt;
              &lt;phone&gt;465456433&lt;/phone&gt;
              &lt;email&gt;gmail1&lt;/email&gt;
          &lt;/staff&gt;
          &lt;staff&gt;
              &lt;area&gt;area1&lt;/area&gt;
              &lt;city&gt;city1&lt;/city&gt;
          &lt;/staff&gt;
      &lt;/company&gt;
  </code></pre>
  
  <p>Expected Output:</p>
  
  <pre><code>    &lt;company&gt;
          &lt;staff&gt;
              &lt;name&gt;john&lt;/name&gt;
              &lt;phone&gt;465456433&lt;/phone&gt;
              &lt;email&gt;gmail1&lt;/email&gt;
              &lt;area&gt;area1&lt;/area&gt;
              &lt;city&gt;city1&lt;/city&gt;
          &lt;/staff&gt;
      &lt;/company&gt;
  </code></pre>