title: How to merge >1000 xml files into one using Java
body: <p>I am trying to merge many xml files into one. I have successfully done that in DOM, but this solution is limited to a few files. When I run it on multiple files >1000 I am getting a java.lang.OutOfMemoryError.</p>
  
  <p>What I want to achieve is where i have the following files</p>
  
  <p>file 1:</p>
  
  <pre><code>&lt;root&gt;
  ....
  &lt;/root&gt;
  </code></pre>
  
  <p>file 2:</p>
  
  <pre><code>&lt;root&gt;
  ......
  &lt;/root&gt;
  </code></pre>
  
  <p>file n:</p>
  
  <pre><code>&lt;root&gt;
  ....
  &lt;/root&gt;
  </code></pre>
  
  <p>resulting in:
  output:</p>
  
  <pre><code>&lt;rootSet&gt;
  &lt;root&gt;
  ....
  &lt;/root&gt;
  &lt;root&gt;
  ....
  &lt;/root&gt;
  &lt;root&gt;
  ....
  &lt;/root&gt;
  &lt;/rootSet&gt;
  </code></pre>
  
  <p>This is my current implementation:</p>
  
  <pre><code>    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
      Document doc = docBuilder.newDocument();
      Element rootSetElement = doc.createElement("rootSet");
      Node rootSetNode = doc.appendChild(rootSetElement);
      Element creationElement = doc.createElement("creationDate");
      rootSetNode.appendChild(creationElement);
      creationElement.setTextContent(dateString); 
      File dir = new File("/tmp/rootFiles");
      String[] files = dir.list();
      if (files == null) {
          System.out.println("No roots to merge!");
      } else {
          Document rootDocument;
              for (int i=0; i&lt;files.length; i++) {
                         File filename = new File(dir+"/"+files[i]);        
                 rootDocument = docBuilder.parse(filename);
                 Node tempDoc = doc.importNode((Node) Document.getElementsByTagName("root").item(0), true);
                 rootSetNode.appendChild(tempDoc);
          }
      }   
  </code></pre>
  
  <p>I have experimented a lot with xslt, sax, but I seem to keep missing something. Any help would be highly appreciated</p>