Java: Fix SAXParseException: :1:1: Content is not allowed in prolog.

Exception Stack Trace:
[Fatal Error] :1:1: Content is not allowed in prolog.
org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.
	at java.xml/com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:262)
	at java.xml/com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:342)
	at org.code2care.java.examples.SAXParseExceptionExample.main(SAXParseExceptionExample.java:21)

You may get the above error when you are trying to parse an XML file in Java using the Sax Parser and the XML file is incorrect.

The most common reason is that you have some text before the <?xml


Incorrect XML file:
data<?xml version="1.0" encoding="UTF-8"?>
<employees>
    <employee>
        <name>Sam Jose</name>
        <dob>1990-05-15</dob>
        <city>New York</city>
    </employee>
...
...

Correct XML file:
<?xml version="1.0" encoding="UTF-8"?>
<employees>
    <employee>
        <name>Sam Jose</name>
        <dob>1990-05-15</dob>
        <city>New York</city>
    </employee>
...
...

There cannot be any text before the <?xml declaration.

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!