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

cei*_*-vg 1 java xml xsd xml-parsing

我试图用Java读取XML文件,然后将其与XML Schema进行比较,但我无法通过此错误:

[致命错误]:1:1:prolog中不允许内容.org.xml.sax.SAXParseException; lineNumber:1; columnNumber:1; 序言中不能有内容.

这是文件读取的开始

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

我通过HEX编辑器扫描了我的XML,但我没有在里面找到任何奇怪的字符,所以我不知道问题出在哪里

将myfile.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>
Run Code Online (Sandbox Code Playgroud)

kjh*_*hes 5

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

更改

Document doc = dBuilder.parse(new InputSource(new StringReader("myfile.xml")));
Run Code Online (Sandbox Code Playgroud)

Document doc = dBuilder.parse(new InputSource("myfile.xml"));
Run Code Online (Sandbox Code Playgroud)