如何在不编组的情况下验证 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.
相关文章