How to validate against schema in JAXB 2.0 without marshalling?(如何在不编组的情况下验证 JAXB 2.0 中的模式?)
问题描述
我需要在编组到 XML 文件之前验证我的 JAXB 对象.在 JAXB 2.0 之前,可以使用 javax.xml.bind.Validator.但这已被弃用,所以我试图找出正确的方法.我熟悉在马歇尔时间进行验证,但就我而言,我只想知道它是否有效.我想我可以编组到一个临时文件或内存并将其丢弃,但想知道是否有更优雅的解决方案.
I need to validate my JAXB objects before marshalling to an XML file. Prior to JAXB 2.0, one could use a javax.xml.bind.Validator. But that has been deprecated so I'm trying to figure out the proper way of doing this. I'm familiar with validating at marshall time but in my case I just want to know if its valid. I suppose I could marshall to a temp file or memory and throw it away but wondering if there is a more elegant solution.
推荐答案
首先,javax.xml.bind.Validator
已被弃用,取而代之的是 javax.xml.validation.Schema
(javadoc).这个想法是您通过 javax.xml.validation.SchemaFactory
(javadoc),并将其注入编组器/解组器.
Firstly, javax.xml.bind.Validator
has been deprecated in favour of javax.xml.validation.Schema
(javadoc). The idea is that you parse your schema via a javax.xml.validation.SchemaFactory
(javadoc), and inject that into the marshaller/unmarshaller.
至于您关于没有编组的验证的问题,这里的问题是 JAXB 实际上将验证委托给 Xerces(或您正在使用的任何 SAX 处理器),并且 Xerces 将您的文档作为 SAX 事件流进行验证.因此,为了验证,您需要执行一些类型的编组.
As for your question regarding validation without marshalling, the problem here is that JAXB actually delegates the validation to Xerces (or whichever SAX processor you're using), and Xerces validates your document as a stream of SAX events. So in order to validate, you need to perform some kind of marshalling.
影响最小的实现是使用 SAX 处理器的/dev/null"实现.编组为空的 OutputStream 仍会涉及 XML 生成,这是一种浪费.所以我建议:
The lowest-impact implementation of this would be to use a "/dev/null" implementation of a SAX processor. Marshalling to a null OutputStream would still involve XML generation, which is wasteful. So I would suggest:
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(locationOfMySchema);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setSchema(schema);
marshaller.marshal(objectToMarshal, new DefaultHandler());
DefaultHandler
将丢弃所有事件,如果对模式的验证失败,marshal()
操作将抛出 JAXBException.
DefaultHandler
will discard all the events, and the marshal()
operation will throw a JAXBException if validation against the schema fails.
这篇关于如何在不编组的情况下验证 JAXB 2.0 中的模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在不编组的情况下验证 JAXB 2.0 中的模式?
- Jersey REST 客户端:发布多部分数据 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01