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
How to validate an XML against schema using JAXB?
提问by AKIWEB
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.
我正在使用XML
,JAXB
因为我正在将 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.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.
您只需要在进行解组之前设置javax.xml.validation.Schema
on 的实例Unmarshaller
。您可以指定ValidationEventHandler
on 的实现Unmarshaller
来捕获在解组过程中发生的任何问题。
For More Information
想要查询更多的信息
I have written more about this use case on my blog:
我在我的博客上写了更多关于这个用例的文章: