title: Java XML parser without excessive memory allocation
body: <p>At work I am parsing large XML files using the <code>DefaultHandler</code> class. Doing that, I noticed that this interface allocates many <code>String</code>s, for element names, attribute names and values, and so on.</p>
  
  <p>From that, I thought about creating an XML parser that only does the absolute minimum of object allocation. Currently I need:</p>
  
  <ul>
  <li>one StringBuilder for building the element names, attribute names, etc.</li>
  <li>one CharsetDecoder for transforming bytes into chars.</li>
  </ul>
  
  <p>My test program, for parsing <a href="http://magnatune.com/info/song_info.xml" rel="nofollow noreferrer">http://magnatune.com/info/song_info.xml</a>, looks like this:</p>
  
  <pre><code>import java.io.BufferedInputStream;
  import java.io.FileInputStream;
  import java.io.IOException;
  import java.io.InputStream;
  import java.util.ArrayList;
  import java.util.LinkedHashMap;
  import java.util.List;
  import java.util.Map;
  
  public class XmlParserDemo {
    public static void main(String[] args) throws IOException {
      List&lt;Map&lt;String, String&gt;&gt; allSongs = new ArrayList&lt;Map&lt;String, String&gt;&gt;();
  
      InputStream fis = new FileInputStream("d:/song_info.xml");
      try {
        XmlParser parser = new XmlParser(new BufferedInputStream(fis));
        if (parser.element("AllSongs")) {
          while (parser.element("Track")) {
            Map&lt;String, String&gt; track = new LinkedHashMap&lt;String, String&gt;();
            while (parser.element()) {
              String name = parser.getElementName();
              String value = parser.text();
              track.put(name, value);
              parser.endElement();
            }
            allSongs.add(track);
            parser.endElement();
          }
          parser.endElement();
        }
      } finally {
        fis.close();
      }
    }
  }
  </code></pre>
  
  <p>This code looks better than my experiments with the <code>XMLEventReader</code>. Now the only missing part would be the <code>XmlParser</code> class mentioned in the code above. Do you know if someone has written that code before? It's really just a pet project of mine, but I'm curious how much the old statement <em>Object creation is expensive</em> is worth anymore.</p>
  
  <p>Yes, I know that <code>LinkedHashMap</code>s are using much memory. It's really just the parsing part that I want to be memory-efficient. Everything else is just for making a simple example.</p>