我用 java 处理 XML 文件。
如果我处理一次 xml 文件,那没关系。总是顺利完成。
但是,如果我处理 xml 文件超过两次(保存 - 读取 - 保存),总是会出现这样的错误。
org.xml.sax.SAXParseException: Content is not allowed in prolog.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:264)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:292)
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:172)
这是我的代码。这段代码有什么问题?
public static boolean save1(String baseDir) throws Exception {
boolean result = true;
File file = new File(baseDir + "myfile.xml");
Document document;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(file);
Element root = document.getDocumentElement();
NodeList nodeList = root.getElementsByTagName("root");
for (int i = 0; i < nodeList.getLength(); i++) {
Element node = (Element) nodeList.item(i);
NamedNodeMap attrs = node.getAttributes();
boolean isDefault = Boolean.valueOf(getText(attrs, "default"));
if (isDefault) {
attrs.getNamedItem("default_value").setNodeValue(Boolean.valueOf("false");
break;
}
}
save(document, file);
return result;
}
private static void save(Document doc, File xmlFile) throws Exception {
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer transformer = tranFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
OutputFormat format = new OutputFormat(doc);
format.setIndenting(true);
format.setIndent(4);
format.setEncoding("utf-8");
format.setPreserveSpace(false);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(xmlFile), "UTF-8"));
XMLSerializer serializer = new XMLSerializer(out, format);
serializer.serialize(doc.getDocumentElement());
out.close();
}