下面列出了怎么用javax.xml.bind.helpers.DefaultValidationEventHandler的API类实例代码及写法,或者点击链接到github查看源代码。
public <T> T fromXML( final InputStream in, final Unmarshaller.Listener listener ) {
try {
final JAXBContext jc = createJAXBContext( additionalClazzes );
final Unmarshaller unmarshaller = jc.createUnmarshaller();
unmarshaller.setEventHandler( new DefaultValidationEventHandler() );
unmarshaller.setListener( listener );
@SuppressWarnings( "unchecked" )
final T result = (T) unmarshaller.unmarshal( in );
return result;
} catch ( final JAXBException e ) {
throw new RuntimeException( e );
}
}
public void toXML( final Object obj, final OutputStream out, final Marshaller.Listener listener ) {
Marshaller marshaller = null;
try {
final JAXBContext jc = createJAXBContext( additionalClazzes );
marshaller = jc.createMarshaller();
marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true );
marshaller.setProperty( MarshallerProperties.NAMESPACE_PREFIX_MAPPER,
new MapNamespacePrefixMapper( NAMESPACE_MAPPINGS ) );
marshaller.setProperty( MarshallerProperties.INDENT_STRING, "\t" );
marshaller.setEventHandler( new DefaultValidationEventHandler() );
marshaller.setListener( listener );
final SessionLogDelegate sessionLog = new SessionLogDelegate( AbstractSessionLog.getLog() );
AbstractSessionLog.setLog( sessionLog );
if ( config.isOnlyFragment() ) {
log.info( "Create only fragment for '{}'.", obj );
marshaller.setProperty( Marshaller.JAXB_FRAGMENT, true );
}
if ( config.isLightweightXml() ) {
log.info( "Use lightweight XML for '{}'.", obj );
lightweightMarshallerSet.add( marshaller );
XmlUtil.addLightWeightAdapter( marshaller );
}
marshaller.marshal( obj, out );
if ( sessionLog.containsMessages() ) {
throw new RuntimeException( "Error persisting XML: " + sessionLog.getLog() );
}
} catch ( final JAXBException e ) {
throw new RuntimeException( e );
} finally {
if ( config.isLightweightXml() && marshaller != null ) {
lightweightMarshallerSet.remove( marshaller );
}
}
}
/** Get a {@link Unmarshaller} instance with the default configuration. */
private Unmarshaller getUnmarshaller() throws JAXBException {
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
unmarshaller.setSchema(schema);
// This handler was the default in JAXB 1.0. It fails on any exception thrown while
// unmarshalling. In JAXB 2.0 some errors are considered recoverable and are ignored, which is
// not what we want, so we have to set this explicitly.
unmarshaller.setEventHandler(new DefaultValidationEventHandler());
return unmarshaller;
}