title: Parsing XML in Java line by line
body: <p>I'd like to parse an XML file in Java <em>line by line</em> because the framework of a file that I got is a bit different than usual. It is not nested; each tag is in its own line.</p>
  
  <p>Part of XML file:</p>
  
  <pre><code>&lt;sentence&gt;&lt;flag&gt;3&lt;/flag&gt;&lt;/sentence&gt;
  &lt;word&gt;&lt;text&gt;Zdravo&lt;/text&gt;&lt;/word&gt;
  &lt;phoneme&gt;&lt;onephoneme&gt;z&lt;/onephoneme&gt;&lt;/phoneme&gt;
  &lt;phoneme&gt;&lt;onephoneme&gt;d&lt;/onephoneme&gt;&lt;/phoneme&gt;
  &lt;phoneme&gt;&lt;onephoneme&gt;r&lt;/onephoneme&gt;&lt;/phoneme&gt;
  &lt;phoneme&gt;&lt;onephoneme&gt;"a:&lt;/onephoneme&gt;&lt;/phoneme&gt;
  &lt;phoneme&gt;&lt;onephoneme&gt;v&lt;/onephoneme&gt;&lt;/phoneme&gt;
  &lt;phoneme&gt;&lt;onephoneme&gt;O&lt;/onephoneme&gt;&lt;/phoneme&gt;
  &lt;sentence&gt;&lt;flag&gt;0&lt;/flag&gt;&lt;/sentence&gt;
  &lt;word&gt;&lt;text&gt;moje&lt;/text&gt;&lt;/word&gt;
  ...
  </code></pre>
  
  <p>I searched and found a lot of different ways to parse an XML file but all of them scan the whole file and I don't want that because my file is almost 100k lines and for now (and maybe even later) I only need first 800 lines so it would be much faster to just parse line by line. I don't know how many lines I really need in advance but I'd like to count how many times I reach tag  and stop at certain count (for now it's 17 - that's around line 800).</p>
  
  <p>Tutorials that I found:</p>
  
  <ul>
  <li>nested XML: <a href="http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/" rel="nofollow noreferrer">http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/</a></li>
  <li>nested XML: <a href="http://www.javacodegeeks.com/2013/05/parsing-xml-using-dom-sax-and-stax-parser-in-java.html" rel="nofollow noreferrer">http://www.javacodegeeks.com/2013/05/parsing-xml-using-dom-sax-and-stax-parser-in-java.html</a></li>
  <li>single line XML with attributes: <a href="https://stackoverflow.com/questions/5231285/read-single-xml-line-with-java">Read single XML line with Java</a></li>
  </ul>
  
  <p>Each sentence is then separated into word and each word into phonemes, so in the end I'd have 3 ArrayLists: flags, words and phonemes.</p>
  
  <p>I hope I gave you enough information.</p>
  
  <p>Thank you.</p>