当我尝试以这种方式从网络解析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的方式有什么问题?
答案 0 :(得分:3)
您在问题中写的代码效果很好
URL url = new URL("http://www.nbp.pl/kursy/xml/a074z120416.xml");
URLConnection uc = url.openConnection();
saxParser.parse(uc.getInputStream(), handler);
我在这里看不到任何问题。也许当你第一次尝试更改文件时,并没有完成。
但现在我可以确认它有效。我试试。