java - fatal error :1:1: Content is not allowed in prolog. org.xml.sax.SAXParseException

标签 java xml xsd xml-parsing

我正在尝试用 Java 读取一个 XML 文件,然后将它与它的 XML 模式进行比较,但我无法克服这个错误:

[Fatal Error] :1:1: Content is not allowed in prolog. org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.

这是文件读取的开始

try {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();          
        Document doc = dBuilder.parse(new InputSource(new StringReader("myfile.xml"))); // ERROR OCCURS HERE

我用HEX Editors扫描了我的XML,但我没有在里面发现任何奇怪的字符,所以我不知道问题出在哪里

我的文件.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<Schedule xmlns ="schedule"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="schedule.xsd">
    <Lesson>
        <Title>Artificial Intelligence</Title>
        <Lecture Classroom="BA">
            <Day>Wednesday</Day>
            <Time>09-11</Time>
        </Lecture>
        <Professor>Hatzilygeroudis</Professor>
    </Lesson>
    <Lesson>
        <Title>Constraint Satisfaction Problems</Title>
        <Lecture Classroom="B3">
            <Day>Monday</Day>
            <Time>19-21</Time>
        </Lecture>
    </Lesson>
    <Lesson>
        <Title>Knowledge Representation in Web</Title>
        <Lecture Classroom="P200">
            <Day>Friday</Day>
            <Time>15-17</Time>
        </Lecture>
        <Professor>Hatzilygeroudis</Professor>
    </Lesson>
    <Lesson>
        <Title>Artificial Intelligence</Title>
        <Lecture>
            <Day>Monday</Day>
            <Time>19-21</Time>
        </Lecture>
    </Lesson>
    <Lesson>
        <Title>AI Programming</Title>
        <Lecture Classroom="B3">
            <Day>Monday</Day>
            <Time>11-13</Time>
        </Lecture>
    </Lesson>
    <Lesson>
        <Title>Introduction to Procedural Programming</Title>
        <Lecture Classroom="P200">
            <Day>Wednesday</Day>
            <Time>15-17</Time>
        </Lecture>
        <Professor>Papadopoulos</Professor>
    </Lesson>
</Schedule>

最佳答案

StringReader("myfile.xml") 采用必须为 XML 的字符串参数,而不是文件名。解析器正在读取字符串文字 myfile.xml(不是 myfile.xml 的文件内容)并立即失败,因为 XML 文档可能不是以 开头>m 字符。

改变

Document doc = dBuilder.parse(new InputSource(new StringReader("myfile.xml")));

Document doc = dBuilder.parse(new InputSource("myfile.xml"));

关于java - fatal error :1:1: Content is not allowed in prolog. org.xml.sax.SAXParseException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47358087/

相关文章:

java - 如何在 XSD 中指定属性 namespace 以便 JAXB 正确解释它?

java - Spring MVC 3.0 + jsp页脚

Java 使用 JAXB 解码对象列表

java - 如何通过脚本/命令在eclipse中开启调试器模式

xml - 如何在 React Native ( JavaScript ) 中创建 XML 文档?

xml - 独立值不会出现在 moxy - jaxb 生成的 xml 中

java - xml:JAXB 中的基础

xml - XML Schema 1.0 中是否有 <assert> 的替代方案

java - XML + XSD => Java?

java - 如何对齐 JTextField 中的文本?