我已经读了一段时间这个SAXParseException错误,并试图解决它,但没有成功。
[Fatal Error] schedule.xml:1:1: Premature end of file.
org.xml.sax.SAXParseException; systemId: file:/U:/schedule.xml; lineNumber: 1; columnNumber: 1; Premature end of file.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
at package.DOMclass.importDocument(DOMclass.java:681) //<---.parse(new File(fileToImport));
...
我已经读到正在使用的流可能是空的(或者正在读取的xml文件是空的),以及它是否可以重用?此外,还存在读取和写回同一文件的问题。这里有一个link对此进行了解释,但我仍然不明白。
另外,另一种可能性可能是我的xml格式错误/不正确,但我查看了它,并且很好,标签很好,并且由于某些原因,我已经将其编码为Notepad ++中的UTF-8(无BOM)帖子说,在xml声明之前可能存在隐藏的空格,但同样,没有成功。
这是我在阅读代码
public TestClass(){
Node root = DOMclass.importDocument("U:\\schedule.xml");
... read nodes, attribute values, etc..
}
public static Document importDocument(String fileToImport)
{
Document document = null;
try
{
document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new File(fileToImport)); //<--- where the error is at
//Do I need a Reader here? to close?
}
catch(SAXException saxe)
{
saxe.printStackTrace();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
catch(ParserConfigurationException pce)
{
pce.printStackTrace();
}
return document;
}
这是我写的。
public static void addNode(String name, String lastName,...){
String filepath = "U;\\schedule.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder;
try {
docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);
...
... make/traverse xml nodes, elements, appending
...
}
DOMUtils.exportDocument(doc, filepath);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void exportDocument(Document documentToExport, String fileName)
{
Transformer transformer = null;
DOMSource domSource = null;
StreamResult streamResult = null;
try
{
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
transformer = TransformerFactory.newInstance().newTransformer();
domSource = new DOMSource(documentToExport);
streamResult = new StreamResult(out);
System.out.println("\nStream Result: " + streamResult);
transformer.transform(domSource, streamResult);
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}
catch(TransformerException e)
{
e.printStackTrace();
}
finally
{
transformer = null;
domSource = null;
streamResult = null;
}
}
}
有什么想法吗?谢谢。