如何使用JAXB针对模式验证XML? [英] How to validate an XML against schema using JAXB?

查看:149
本文介绍了如何使用JAXB针对模式验证XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 XML JAXB ,因为我正在解组并将XML编组为Java对象,反之亦然。现在我试图根据我们的模式验证我们的XML(test.xsd)。假设我的XML中缺少任何必填字段,那么我想知道在针对模式test.xsd验证XML之后缺少哪个字段。

I am working with XML and JAXB as I am unmarshalling and marshalling the XML into Java objects and vice versa. Now I am trying to validate our XML against our schema(test.xsd). Suppose if any required field is missing in my XML, then I would like to know which field is missing after validating the XML against schema test.xsd.

public void unmarshal(final InputStream is) {
    final XMLInputFactory factory = XMLInputFactory.newInstance();
    final XMLStreamReader reader = factory.createXMLStreamReader(is);

    Object req = unmarshaller.unmarshal(reader);

    // how would I validate here?
}

我如何根据test.xsd架构验证我的XML。我的test.xsd架构路径是 -

How would I validate my XML against test.xsd schema. My test.xsd schema path is -


C:\ workspace \ one\two\three\src \ main \ java\com\package\serv\ap\versionOne\test.xsd

C:\workspace\one\two\three\src\main\java\com\package\serv\ap\versionOne\test.xsd

更新:将test.xsd加载为:

Schema schema = factorySchema.newSchema(new File("C:\\workspace\\one\\two\\three\\src\\main\\java\\com\\package\\serv\\ap\\versionOne\\test.xsd"));


推荐答案

您只需要设置 javax.xml.validation.Schema Unmarshaller 上执行。您可以在 Unmarshaller 上指定 ValidationEventHandler 的实现,以捕获在解组过程中发生的任何问题。

You just need to set an instance of javax.xml.validation.Schema on the Unmarshaller before you do the unmarshal. You can specify an implementation of ValidationEventHandler on the Unmarshaller to catch any problems that occur during the unmarshal process.

  • http://docs.oracle.com/javase/7/docs/api/javax/xml/bind/Unmarshaller.html#setSchema%28javax.xml.validation.Schema%29

更多信息

我在博客上写了更多关于这个用例的信息:

I have written more about this use case on my blog:

  • http://blog.bdoughan.com/2010/12/jaxb-and-marshalunmarshal-schema.html

这篇关于如何使用JAXB针对模式验证XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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