0

I've handling XML file with java.

If i handle xml file once, that is ok. Always successfully done.

But, if i handle xml file more than twice(save - read - save), always get error like this.

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)

this is my code. what is the problem this code?

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();
}
  • Without seeing the content of the claimed XML file it is impossible to be sure of the cause of the problem. But the save-read-save operation might be introducing a BOM or changing the encoding. – Raedwald Jul 18 '14 at 10:12
  • The relevant canonical question is http://stackoverflow.com/questions/5138696/org-xml-sax-saxparseexception-content-is-not-allowed-in-prolog – Raedwald Jul 18 '14 at 10:13

1 Answers1

1

The message "Content is not allowed in prolog." can mean a great many things; it's common to get this message if you try to read an empty file, or a file whose content is not XML at all.

I can't see what's wrong from this sample, but I would start by displaying the (supposed) XML that can't be parsed.

Michael Kay
  • 156,231
  • 11
  • 92
  • 164