在jaxb中使用xsd进行xml验证



我有一个xml。我已经为xml创建了一个XSD。

我想编写一个程序来根据xsd验证xml。我写了一个程序,得到了个人价值观的设定。

但是,有没有一种方法,我可以将xml文件作为输入,并查看xml是否对XSD有效?

谢谢,Nini

这是一个使用XSD进行xml验证的示例。

public static boolean validate() {
    Source xmlFile = null;
    File schemaFile;
    SchemaFactory schemaFactory;
    Schema schema;
    try {
        schemaFile = new File(xsdFileName);
        xmlFile = new StreamSource(new File(xmlFileName));
        schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        schema = schemaFactory.newSchema(schemaFile);
        Validator validator = schema.newValidator();
        validator.validate(xmlFile);
        System.out.println(xmlFile.getSystemId() + " is valid");
    } catch (SAXException | IOException e) {
        System.out.println(xmlFile.getSystemId() + " is NOT valid");
        System.out.println("Reason: " + e.getLocalizedMessage());
        return false;
    }
    return true;
}

最新更新