Java 如何使用 JAXB 根​​据模式验证 XML?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24760796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 14:43:39  来源:igfitidea点击:

How to validate an XML against schema using JAXB?

javaxmljaxbxsdunmarshalling

提问by AKIWEB

I am working with XMLand JAXBas 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.

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

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?
}

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

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

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

UPDATE: loading test.xsd as:

更新:加载 test.xsd 为:

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

采纳答案by bdoughan

You just need to set an instance of javax.xml.validation.Schemaon the Unmarshallerbefore you do the unmarshal. You can specify an implementation of ValidationEventHandleron the Unmarshallerto catch any problems that occur during the unmarshal process.

您只需要在进行解组之前设置javax.xml.validation.Schemaon 的实例Unmarshaller。您可以指定ValidationEventHandleron 的实现Unmarshaller来捕获在解组过程中发生的任何问题。

For More Information

想要查询更多的信息

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

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