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 中的模式?
基础教程推荐
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 降序排序:Java Map 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01