org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog,saxparseexception
用sax讀xml檔案時常會出現這個異常,一般上網可以看到的原因是:
1.BOM
在java中測試inputstream中是否有bom可以用apache commons IO 的org.apache.commons.io.input.BOMInputStream,如果你的項目有引入IO的情況下
BOM的基礎知識可以參考:http://www.unicode.org/faq/utf_bom.html
也貼一個過濾BOM的小方法
private static InputStream checkForUtf8BOMAndDiscardIfAny(InputStream inputStream) throws IOException { PushbackInputStream pushbackInputStream = new PushbackInputStream(new BufferedInputStream(inputStream), 3); byte[] bom = new byte[3]; if (pushbackInputStream.read(bom) != -1) { if (!(bom[0] == (byte) 0xEF && bom[1] == (byte) 0xBB && bom[2] == (byte) 0xBF)) { pushbackInputStream.unread(bom); } } return pushbackInputStream; }
2.非良構的xml內容,例如在<?xml前出現非法的字元
可以採用正則從<?xml開始截取內容
3.今天我發現的是因為:Accept-Encoding啟用了壓縮傳輸,可以試著把Accept-Encoding設成:identity,同時也要注意是否採用Chunked Transfer Encoding(分段傳輸)
後話,有人說直接把流傳給sax parser可以過濾掉。當然我用的sax,jaxp發現不會過濾掉。文檔測試的環境:java 7 + xerces sax。全部異常棧
org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)at org.apache.xerces.util.ErrorHandlerWrapper.fatalError(Unknown Source)at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)at org.apache.xerces.impl.XMLScanner.reportFatalError(Unknown Source)at org.apache.xerces.impl.XMLDocumentScannerImpl$PrologDispatcher.dispatch(Unknown Source)at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)at org.apache.xerces.jaxp.SAXParserImpl.parse(Unknown Source)