【问题标题】:JSP: SAXParseException - Content is not allowed in prologJSP:SAXParseException - prolog 中不允许有内容
【发布时间】:2016-09-06 17:26:14
【问题描述】:

我想用下面的jsp脚本解析一个xml文件:

<%@ page contentType="text/html; charset=utf-8" language="java" %>
<%@ page import="javax.xml.parsers.DocumentBuilderFactory" %>
<%@ page import="javax.xml.parsers.DocumentBuilder" %>
<%@ page import="org.xml.sax.SAXParseException" %>
<%@ page import="java.io.File" %>
<%@ page import="java.io.InputSource" %>
<%@ page import="java.io.StringReader" %>
<%@ page import="org.w3c.dom.Document" %>
<%
try
{
    String xmlFileURI = "test\\foo.xml";
    File file = new File (xmlFileURI);
    if (file.exists ())
    {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ();
        DocumentBuilder builder = factory.newDocumentBuilder ();
        InputSource is = new InputSource (new StringReader (xmlFileURI));
        Document document = builder.parse (is);
    }
}
catch (IOException ioEx)
{
    out.println ("<p>");
    out.println("IOException: " + ioEx.getMessage ());
}
catch (SAXParseException saxEx)
{
    out.println ("<p>");
    out.println("SAXParseException: " + saxEx);
}
%>

但是,带有

的行
builder.parse (is);

总是抛出这个异常:

org.xml.sax.SAXParseException;行号:1;列号:1;序言中不允许有内容。

我发现很多其他人已经遇到过这个问题,但他们似乎主要是由于他们的 xml 文件中有 BOM。我打印出文件的十六进制值,它以

开头

3c 3f 78 6d 20 76 等

所以我觉得很好。

我的 xml 看起来像这样

<?xml version="1.0" encoding="UTF-8"?>
<foo>
    <bar>asdf</bar>
    <foobar>asdf</foobar>
</foo>

位于C:\Tomcat8.0\test。我还尝试使用xmlFileURI 的绝对路径,但结果相同。

任何想法我做错了什么?

【问题讨论】:

  • 看起来 Java StringReader 接受字符串,不是 URI 文件,其内容将被读取为字符串。因此,在这种情况下,您的代码将值“test\\foo.xml”传递给builder.parse(),而不是传递foo.xml 文件的字符串内容,因此会出现错误。
  • 不,builder.parse(file) 导致相同的异常。
  • 等一下,builder.parse(file) 确实有效!我没有意识到我必须为此重新启动 Tomcat。谢谢!
  • 太好了,你解决了!我将我的评论转换为答案,以便可以正确关闭此问题

标签: xml jsp


【解决方案1】:

看起来 Java StringReader 接受字符串,不是 URI 到文件,其内容将被读取为字符串。所以在这种情况下,您的代码将值“test\foo.xml”传递给builder.parse(),而不是传递“foo.xml”文件的字符串内容,因此会出现错误。

也就是说,请改用builder.parse(file)*:

String xmlFileURI = "test\\foo.xml";
File file = new File (xmlFileURI);
if (file.exists ())
{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(file);
}

*) 不是 Java 程序员,是从 here 得到的想法。并且不要忘记重新启动 Tomcat,如 OP 所述,以使此更改生效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-01
    • 2011-07-23
    • 1970-01-01
    • 2015-12-15
    • 2011-04-09
    • 2019-04-04
    • 1970-01-01
    相关资源
    最近更新 更多