title: How to modify a huge XML file by StAX?
body: <p>I have a huge XML (~2GB) and I need to add new Elements and modify the old ones. For example, I have:</p>
  
  <pre><code>&lt;books&gt;
      &lt;book&gt;....&lt;/book&gt;
      ...
      &lt;book&gt;....&lt;/book&gt;
  &lt;/books&gt;
  </code></pre>
  
  <p>And want to get:</p>
  
  <pre><code>&lt;books&gt;
     &lt;book&gt;
        &lt;index&gt;&lt;/index&gt;
        ....
     &lt;/book&gt;
     ...
     &lt;book&gt;
        &lt;index&gt;&lt;/index&gt;
        ....
     &lt;/book&gt;
  &lt;/books&gt;
  </code></pre>
  
  <p>I used the following code:</p>
  
  <pre><code>XMLInputFactory inFactory = XMLInputFactory.newInstance();
  XMLEventReader eventReader = inFactory.createXMLEventReader(new FileInputStream(file));
  XMLOutputFactory factory = XMLOutputFactory.newInstance();
  XMLStreamWriter writer = factory.createXMLStreamWriter(new FileWriter(file, true));
  while (eventReader.hasNext()) {
     XMLEvent event = eventReader.nextEvent();
     if (event.getEventType() == XMLEvent.START_ELEMENT) {
        if (event.asStartElement().getName().toString().equalsIgnoreCase("book")) {
            writer.writeStartElement("index");
            writer.writeEndElement();
         }
      }
  }
  writer.close();
  </code></pre>
  
  <p>But the result was the following:</p>
  
  <pre><code>&lt;books&gt;
     &lt;book&gt;....&lt;/book&gt;
     ....
     &lt;book&gt;....&lt;/book&gt;
  &lt;/books&gt;&lt;index&gt;&lt;/index&gt;
  </code></pre>
  
  <p>Any ideas?</p>