验证使用jaxb针对xsd文件创建的xml [英] Validate xml created using jaxb against an xsd file

查看:147
本文介绍了验证使用jaxb针对xsd文件创建的xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用jaxb创建的xml文件。我需要针对xsd文档验证它。是否可以在没有解组的情况下进行验证。然后我需要在xml文件中打印错误。

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.5中的java中的验证器。这里是参考 doc

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

除此之外,您还可以使用基于dom或基于流的API来针对xsd文件验证XML文档。
如果您希望将SAX API用于您的任务,那么请听听示例:

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());
}

否则你可以使用DOM,DOM4J或XOM API。如需进一步参考,请参阅 此处

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

有一个相关的 answer

这篇关于验证使用jaxb针对xsd文件创建的xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆