1

我正在尝试针对 Java 中的 XSD 文件验证 XML。

这是我的代码:

public static InputStream inputStreamFromClasspath(String path) {
    return Utils.class.getClassLoader().getResourceAsStream(path);
}   

public static boolean validateXMLSchema() throws SAXException, IOException {

    InputStream xsd = inputStreamFromClasspath("/xml/students_xsd.xml");
    InputStream xml = inputStreamFromClasspath("/xml/students.xml");
    SchemaFactory factory =
                SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = factory.newSchema(new StreamSource(xsd));
    Validator validator = schema.newValidator();
    validator.validate(new StreamSource(xml));
    return true;
}

但我收到一个错误:

org.xml.sax.SAXParseException; schema_reference.4: Failed to read schema document 'null', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.

代码参考:针对 XSD 验证 XML

我的学生 xml 文件是:

<?xml version = "1.0"?>

<class>
    <student rollno = "393">
        <firstname>Dinkar</firstname>
        <lastname>Kad</lastname>
        <nickname>Dinkar</nickname>
        <marks>85</marks>
    </student>

    <student rollno = "493">
        <firstname>Vaneet</firstname>
        <lastname>Gupta</lastname>
        <nickname>Vinni</nickname>
        <marks>95</marks>
    </student>

    <student rollno = "593">
        <firstname>Jasvir</firstname>
        <lastname>Singh</lastname>
        <nickname>Jazz</nickname>
        <marks>90</marks>
    </student>
</class>

xsd文件是:

<?xml version = "1.0"?>

<xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema">
    <xs:element name = 'class'>
        <xs:complexType>
            <xs:sequence>
                <xs:element name = 'student' type = 'StudentType' minOccurs = '0'
                            maxOccurs = 'unbounded' />
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:complexType name = "StudentType">
        <xs:sequence>
            <xs:element name = "firstname" type = "xs:string"/>
            <xs:element name = "lastname" type = "xs:string"/>
            <xs:element name = "nickname" type = "xs:string"/>
            <xs:element name = "marks" type = "xs:positiveInteger"/>
        </xs:sequence>
        <xs:attribute name = 'rollno' type = 'xs:positiveInteger'/>
    </xs:complexType>
</xs:schema>

不知道我哪里错了,任何建议都会有所帮助。谢谢你。

4

1 回答 1

3

另一件事:

    InputStream xsd = inputStreamFromClasspath("/xml/students_xsd.xml");
    return Utils.class.getClassLoader().getResourceAsStream(path);
  • ClassLoader 使用没有前面的绝对路径/
  • 一个类使用一个可能的相对路径(相对于它的包),并且对于绝对路径需要一个前面的/.

要么(我的偏好,模块化java更好)

    InputStream xsd = inputStreamFromClasspath("/xml/students_xsd.xml");
    return Utils.class.getResourceAsStream(path);

或(需要更正所有调用)

    InputStream xsd = inputStreamFromClasspath("xml/students_xsd.xml");
    return Utils.class.getClassLoader().getResourceAsStream(path);

null由于该斜线,您获得了资源。

于 2022-02-03T21:17:58.907 回答