Validate xml created using jaxb against an xsd file

半城伤御伤魂 提交于 2020-01-21 01:44:37

问题


I have a xml file created using jaxb. I need to validate it against a xsd document. Is it possible to just do validation without unmarshalling. I need to then print the errors in the xml file.


回答1:


Yes you can use validator found in java from 1.5. here is the reference doc

Apart from it you can use dom based or stream based API to validate your XML document against xsd file. If you wish to use SAX API for your task then hear is the example:

try {
    String schemaLang = "http://www.w3.org/2001/XMLSchema";

    SchemaFactory factory = SchemaFactory.newInstance(schemaLang);

    Schema schema = factory.newSchema(new StreamSource("sample.xsd"));
    Validator validator = schema.newValidator();

    validator.validate(new StreamSource("test.xml"));

} catch (SAXException e) {
    System.out.println(" sax exception :" + e.getMessage());
} catch (Exception ex) {
    System.out.println("excep :" + ex.getMessage());
}

Otherwise you can use DOM, DOM4J or XOM API. For further reference you can see here.

There is a related answer in stackoverflow also.



来源:https://stackoverflow.com/questions/10944332/validate-xml-created-using-jaxb-against-an-xsd-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!