我有兩個方法下面的類。 openInputStream
創建一個輸入流,然後將其輸入到readDocument
中以從該流創建XML文檔。如何修復錯誤「序言中不允許org.xml.sax.SAXParseException/Content」?
public class XmlReader {
protected InputStream openInputStream(final String path)
throws IOException {
final InputStream inputStream;
inputStream = IOUtils.toInputStream(path, "UTF-8");
return inputStream;
}
protected Document readDocument(final InputStream stream)
throws ParserConfigurationException, SAXException, IOException {
final DocumentBuilderFactory dbfac =
DocumentBuilderFactory.newInstance();
final DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
return docBuilder.parse(stream);
}
}
然後,我有以下測試:
public class XmlReaderTests {
@Test
public void parsingOfMapFiles() throws IOException,
SAXException, ParserConfigurationException {
final String[] dirs = new String[] {
"01_Phoenix1",
"02_Phoenix2",
"03_Guadalupe",
"04_SanDiego_MiramarRoad",
"05_Berlin_Alexanderplatz",
"06_Portland_ForestAvenue",
"07_Hartford_LafayetteHudsonStreet",
"08_FortWorth",
"09_Charleston_CalhounStreetMeetingStreet",
"10_LosAngeles_PershingSquare",
"11_Uelzen"
};
for (final String dir : dirs) {
final XmlReader objectUnderTest = new XmlReader();
final String path =
String.format("src/test/resources/mc/E-2015-10-13_1/%s/map.osm",
dir);
final File file = new File(path);
Assert.assertTrue(file.canRead());
final InputStream inputStream =
objectUnderTest.openInputStream(file.getAbsolutePath());
final Document doc = objectUnderTest.readDocument(inputStream);
Assert.assertNotNull(doc);
}
}
}
readDocument
拋出異常
org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog. at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:257) at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:347) at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:121) at XmlReader.readDocument(XmlReader.java:26) at XmlReaderTests.parsingOfMapFiles(XmlReaderTests.java:40)
你可以找到源代碼,我嘗試讀取XML文件here。
我該如何解決這個錯誤?
更新1:更改openStream
到
protected InputStream openInputStream(final String path)
throws IOException {
return new BOMInputStream(IOUtils.toInputStream(path, "UTF-8"));
}
或
protected InputStream openInputStream(final String path)
throws IOException {
return new BOMInputStream(IOUtils.toInputStream(path));
}
沒有幫助。
更新2:
如果我改變openInputStream
方式類似
protected InputStream openInputStream(final String path)
throws IOException {
BOMInputStream inputStream = new BOMInputStream(IOUtils.toInputStream(path, "UTF-8"));
System.out.println("BOM: " + inputStream.hasBOM());
return inputStream;
}
我得到這樣的輸出:
BOM: false [Fatal Error] :1:1: Content is not allowed in prolog.
看看這裏: –
Terrence
@Terrence謝謝。看到我的更新1. –
可能是你的XML文件沒有welformed(或空)。在這裏檢查:www.xmlvalidation。com –