How to validate an XML against schema using JAXB?(如何使用 JAXB 针对模式验证 XML?)
问题描述
我正在使用 XML
和 JAXB
,因为我正在将 XML 解组和编组为 Java 对象,反之亦然.现在我正在尝试根据我们的模式(test.xsd)验证我们的 XML.假设如果我的 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:workspaceone wo hreesrcmainjavacompackageservapversionOne est.xsd
C:workspaceone wo hreesrcmainjavacompackageservapversionOne est.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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 JAXB 针对模式验证 XML?
- Jersey REST 客户端:发布多部分数据 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01