0

我用 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();
}
4

1 回答 1

1

消息“序言中不允许内容”。可能意味着很多事情;如果您尝试读取空文件或内容根本不是 XML 的文件,通常会收到此消息。

从这个示例中我看不出有什么问题,但我将从显示无法解析的(假定的)XML 开始。

于 2013-07-08T07:51:37.253 回答