致命错误:1:1:内容不允许在prolog中.org.xml.sax.SAXParseException.



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

[致命错误] :1:1:内容不允许在prolog中使用。 org.xml.sax.SAXParseException;行号: 1;列数: 1;内容不允许在 prolog 中使用。

这是文件读取的开始

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

我通过十六进制编辑器扫描了我的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"));

您可能有一个带有字节顺序标记 (BOM( 的 UTF-8 文件。它对大多数编辑器来说是不可见的,但可能会弄乱解析器。尝试转换为不带 BOM 表的 UTF-8。

相关内容

最新更新