"Premature end of file, org. xml. sax. SAXParseException"异常的原因是什么?



>我正在使用 sax 创建一个 xml 文件,但是当我运行该程序时,发生以下错误:

[Fatal Error] :-1:-1: Premature end of file.
org.xml.sax.SAXParseException; Premature end of file.
at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:205)

我检查了写入的文件,但没有看到任何问题。以下是我的代码和操作的 xml 文件。

1. 代码

以下代码的主要逻辑是:创建一个 XML 节点,然后将该节点追加到旧文件中。


import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class XmlWriterByDom {
private static final XMLConfigUtils xmlConfig = XMLConfigUtils.getInstance();
public void xmlInsert(Map<String, String> xmlNode, String xmlPath) {
Document doc = xmlConfig.getDocument(xmlPath);
Text nodeValue;
Element root = doc.getDocumentElement();
Element food = doc.createElement(XmlTag.FOOD);
Element name = doc.createElement(XmlTag.NAME);
Element price = doc.createElement(XmlTag.PRICE);
Element desc = doc.createElement(XmlTag.DESC);
nodeValue = doc.createTextNode(xmlNode.get(XmlTag.FOOD));
name.appendChild(nodeValue);
food.appendChild(name);
nodeValue = doc.createTextNode(xmlNode.get(XmlTag.PRICE));
price.appendChild(nodeValue);
food.appendChild(price);
nodeValue = doc.createTextNode(xmlNode.get(XmlTag.DESC));
desc.appendChild(nodeValue);
food.appendChild(desc);
root.appendChild(food);
try {
xmlPath = Objects.requireNonNull(               this.getClass().getClassLoader().getResource(xmlPath)).getPath();
TransformerFactory transformer = TransformerFactory.newInstance();
Transformer trans = transformer.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(xmlPath).toURI().getPath());
trans.transform(source, result);
} catch (TransformerException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Map<String, String> xmlNode = new HashMap<>(3);
xmlNode.put("name", "tomato");
xmlNode.put("price", "$10");
xmlNode.put("description", "dishes");
new XmlWriterByDom().xmlInsert(xmlNode, "xml/henan-dishes.xml");
}
}

2.XML

<?xml version="1.0" encoding="UTF-8" ?>
<menu>
<food>
<name>1</name>
<price>18$</price>
<description>2</description>
</food>
<food>
<name>1</name>
<price>59$</price>
<description>2</description>
</food>
</menu>

当我尝试删除具有目标名称的已编译文件夹并重新执行时,结果是正确的。可能真的是文件系统有问题! 项目结构