[java] org.xml.sax.SAXParseException: Content is not allowed in prolog

Sometimes it's the code, not the XML

The following code,

Document doc = dBuilder.parse(new InputSource(new StringReader("file.xml")));

will also result in this error,

[Fatal Error] :1:1: Content is not allowed in prolog.org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.

because it's attempting to parse the string literal, "file.xml" (not the contents of the file.xml file) and failing because "file.xml" as a string is not well-formed XML.

Fix: Remove StringReader():

Document doc = dBuilder.parse(new InputSource("file.xml"));

Similarly, dirty buffer problems can leave residual junk ahead of the actual XML. If you've carefully checked your XML and are still getting this error, log the exact contents being passed to the parser; sometimes what's actually being (tried to be) parsed is surprising.