title: Parsing an XML stream with no root element
body: <p>I need to parse a continuous stream of well-formed XML elements, to which I am only given an already constructed <code>java.io.Reader</code> object. These elements are not enclosed in a root element, nor are they prepended with an XML header like <code>&lt;?xml version="1.0"?&gt;"</code>, but are otherwise valid XML.</p>
  
  <p>Using the Java <code>org.xml.sax.XMLReader</code> class does not work, because the XML Reader expects to parse well-formed XML, starting with an enclosing root element. So, it just reads the first element in the stream, which it perceives as the root, and fails in the next one, with the typical</p>
  
  <blockquote>
    <p>org.xml.sax.SAXParseException: The markup in the document following the root element must be well-formed.</p>
  </blockquote>
  
  <p>For files that do not contain a root element, but where such element does exist or can be defined (and is called, say, MyRootElement), one can do something like the following:</p>
  
  <pre><code>        Strint path = &lt;the full path to the file&gt;;
  
          XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
  
          StringBuilder buffer = new StringBuilder();
  
          buffer.append("&lt;?xml version=\"1.0\"?&gt;\n");
          buffer.append("&lt;!DOCTYPE MyRootElement ");
          buffer.append("[&lt;!ENTITY data SYSTEM \"file:///");
          buffer.append(path);
          buffer.append("\"&gt;]&gt;\n");
          buffer.append("&lt;MyRootElement xmlns:...&gt;\n");
          buffer.append("&amp;data;\n");
          buffer.append("&lt;/MyRootElement&gt;\n");
  
          InputSource source = new InputSource(new StringReader(buffer.toString()));
  
          xmlReader.parse(source);
  </code></pre>
  
  <p>I have tested the above by saving part of the <code>java.io.Reader</code> output to a file and it works. However, this approach is not applicable in my case and such extra information (XML header, root element) cannot be inserted, since the <code>java.io.Reader</code> object passed to my code is already constructed.</p>
  
  <p>Essentially, I am looking for "fragmented XML parsing". So, my question is, can it be done, using standard Java APIs (including the <code>org.sax.xml.*</code> and <code>java.xml.*</code> packages)?</p>