1

I am having trouble parsing an XML file into a JDOM Document instance using the SAXBuilder.

It throws the following exception:

[Fatal Error] :1:1: Content is not allowed in prolog.

I have found and read all those threads on Stack Exchange and on other places in the Internet and tried various things to debug the error.

I have end up with the following code snippet, which throws as well.

String template = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<server></server>";
InputStream in = new StringBufferInputStream(template);
return saxBuilder.build(in);

What's wrong with it?


I am ashamed to admit that but it turned out that the error wasn't produced by the snippet I have shown here but rather at a later point where I was comparing the parsed XML against another one using the XMLUnit library.

The think that made me believe that the error was in the presented lines was the content of the error message.

I believe it would be appropriate to close (and delete, if that's possible) this question as it does not mean any value.

4

2 回答 2

1

此错误通常意味着您的 xml 声明之前有文本。

在您的代码段中,xml 似乎很好。但问题可能不在您的文档中。如果您有架构或其他引用的 xml 文件,则错误实际上可能涉及其中之一。

于 2012-07-09T12:20:02.847 回答
1

我怀疑问题出在其他地方。以下代码(使用dom4j)适用于我:

public static void main(String[] args) throws DocumentException {
    String template = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<server></server>";
    SAXReader saxReader = new SAXReader();
    InputStream is = new StringBufferInputStream(template);
    Document document = saxReader.read(is);
    System.out.println(document.asXML());
}

另请注意,StringBufferInputStream已弃用。另一种选择是

        StringReader sr = new StringReader(template);
        Document document = saxReader.read(sr);

所以,问题不在于您的 XML 片段,而可能在于saxBuilder.build(...)

于 2012-07-09T12:26:38.283 回答