SoFunction
Updated on 2025-03-03

DOM parsing XML error Content is not allowed in prolog solution detailed explanation

The error content is:

Content is not allowed in prolog. Nested exception: Content is not allowed in prolog

To sum up online, it means that the content of the analysis contains BOM. This mark is not visible, it is just a mark in the stream.

BOM: Byte Order Mark, Chinese name and byte order mark. The UCS specification recommends that before transmitting a byte stream, the BOM is transmitted to determine the byte order.

In fact, UTF-8 does not need to use BOM to indicate byte order, but BOM can be used to indicate encoding method. The UTF-8 encoding of the BOM is EF BB BF, so if the recipient receives a byte stream starting with EF BB BF, it means it is UTF-8 encoding.

Solution:

If the file is parsed:

You can open XML with UltraEdit or EmEditor and save as. When saving, there is an option to save it as UTF-8 without BOM or UTF-8 with BOM.

If it is back from a remote request:

Then you can't see the BOM when you turn the returned stream New as a string, but you must intercept the content you need:

if(null != result && !"".equals(result)){ 
  if(("<") != -1 && (">") != -1 && (">") > ("<")) 
    result = (("<"), (">") + 1); 
} 

Some people also say that it is caused by the low DOM4J version, but I looked at the version I used is 1.6.1, so I ruled out this possibility, but in reality I still recommend using the latest stable version for development.

renew

Today I looked at the log and found that my exception was not caused by the BOM header. Fortunately, I also printed the content I received. When I looked, I went, the server returned an error string directly after the processing failed. I mianed it for a while, and it was indeed an error. This is a tricky thing.

public static void main(String[] args) throws DocumentException { 
  String str = "error"; 
  Document doc = (str); 
  (()); 
} 

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.