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

查看:83
本文介绍了针对 xsd 文件验证使用 jaxb 创建的 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.

推荐答案

是的,您可以使用 Java 1.5 中的验证器.这是参考 文档

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 也在 stackoverflow 中.

There is a related answer in stackoverflow also.

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

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