1

当我尝试以这种方式从网络解析 XML 文件时:

URL url = new URL("http://www.nbp.pl/kursy/xml/a074z120416.xml");
URLConnection uc = url.openConnection();
saxParser.parse(uc.getInputStream(), handler);

文件异常的过早结束正在抛出。

堆栈跟踪:

org.xml.sax.SAXParseException: Premature end of file.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at javax.xml.parsers.SAXParser.parse(Unknown Source)
at javax.xml.parsers.SAXParser.parse(Unknown Source)
at com.pmajcher.xmltest.ReadXMLFile.main(ReadXMLFile.java:142)

但是当我第一次将该 xml 保存到本地文件,然后尝试解析它时,一切正常。

URL url = new URL("http://www.nbp.pl/kursy/xml/a074z120416.xml");
URLConnection uc = url.openConnection();
InputStreamReader input = new InputStreamReader(uc.getInputStream());
BufferedReader in = new BufferedReader(input);
File file = new File("temp.xml");

if(!file.exists()){
    file.createNewFile();
}

PrintWriter out = new PrintWriter(file);
String inputLine;

while ((inputLine = in.readLine()) != null) {
    out.print(inputLine);
}
out.close();
saxParser.parse("temp.xml", handler);

我尝试从网上解析 xml 的方式有什么问题?

4

1 回答 1

3

您在问题中编写的代码运行良好

URL url = new URL("http://www.nbp.pl/kursy/xml/a074z120416.xml");
URLConnection uc = url.openConnection();
saxParser.parse(uc.getInputStream(), handler);

我在这里看不出任何问题。也许当您第一次尝试时文件正在更改并且不完整。

但现在我可以向你确认它有效。我试试看。

于 2012-04-16T18:08:04.617 回答