我正在尝试从 jsp 文件中读取 xml 文件。它们都在同一个目录下,我正在使用 BufferReader 从 xml 文件中读取。 我收到错误“第 3 行第 6 列的错误:仅在文档开头允许的 xml 声明”。在网上搜索原因,我得到的只是 xml 文件不应该以新行开头,但我检查了我的 xml,删除了开头的每个空格。 这是我程序中唯一的 xml 文件,所以我真的不知道可能是什么问题。 我正在添加我的 xml 文件和我的 jsp 文件。我可能做错了什么,但我不知道是什么。
我的 xml 文件:
<?xml version="1.0"encoding="UTF-8"?>
<quiz>
<question type="multichoice" >
<name>
<text>Name of question</text>
</name>
<questiontext format="html">
<text>What is the answer to this question?</text>
</questiontext>
<answer fraction="100">
<text>The correct answer</text>
<feedback><text>Correct!</text></feedback>
</answer>
<answer fraction="0">
<text>A distractor</text>
<feedback><text>Ooops!</text></feedback>
</answer>
<answer fraction="0">
<text>Another distractor</text>
<feedback><text>Ooops!</text></feedback>
</answer>
<shuffleanswers>1</shuffleanswers>
<single>true</single>
<answernumbering>abc</answernumbering>
</question>
<question type="truefalse">
<name>
<text>Name of question</text>
</name>
<questiontext format="html">
<text>What is the answer to this question?</text>
</questiontext>
<answer fraction="100">
<text>true</text>
<feedback><text>Correct!</text></feedback>
</answer>
<answer fraction="0">
<text>false</text>
<feedback><text>Ooops!</text></feedback>
</answer>
</question>
<question type="numerical">
<name>
<text>Name of question</text>
</name>
<questiontext format="html">
<text>What is the answer to this question?</text>
</questiontext>
<answer fraction="100">
<text>23</text>
<feedback><text>Feedback</text></feedback>
</answer>
</question>
</quiz>
xml定义前没有空格(文件第一行)。 和我的 jsp 文件:
<%@ page contentType="text/xml" %>
<%@ page import="java.io.*" %>
<%
//dump out the file
BufferedReader in = new BufferedReader(new FileReader("questions.xml"));
String line;
while((line = in.readLine())!=null){
out.print(line);
}
in.close();
%>
我是使用 java 进行 html 编程的新手,所以如果你能帮助我就太好了......谢谢
最佳答案
我假设您在导航到 JSP 页面时在浏览器中看到了该错误。问题出在 JSP 顶部的页面指令中
<%@ page contentType="text/xml" %>
<%@ page import="java.io.*" %>
因为每一个后面都有一个换行符,你最终会在数据(由 out.println
语句写入)之前将两个换行符写入 out
,这就是为什么错误消息说您在第 3 行有一个 XML 声明。
删除换行符,或者将它们移动到指令内部而不是它们之间应该可以解决这个问题:
<%@ page contentType="text/xml"
%><%@ page import="java.io.*"
%><%
BufferedReader ....
顺便说一句,为了读取文件,您应该使用 FileInputStream
(或更好的 application.getResourceAsStream
)和明确设置的 InputStreamReader
到正确的字符编码以匹配 XML 文件,而不是依赖始终使用平台默认编码的 FileReader
。
关于java - xml 声明只允许在文档的开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15312843/