如何在没有编组的情况下验证JAXB 2.0中的模式? [英] How to validate against schema in JAXB 2.0 without marshalling?

查看:88
本文介绍了如何在没有编组的情况下验证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 (< a href =https://docs.oracle.com/javase/7/docs/api/javax/xml/validation/Schema.html\"rel =noreferrer> javadoc )。我们的想法是通过 javax.xml.validation.SchemaFactory 解析您的架构( javadoc ),并将其注入marshaller / unmarshaller。

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.

这对影响最小的实现是使用 / dev / nullSAX处理器的实现。编组为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中的模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆